Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: rewards stats passing #162

Merged
merged 1 commit into from
May 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 15 additions & 20 deletions taraxa/C/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ package main
//#include <rocksdb/c.h>
import "C"
import (
"fmt"
"math/big"
"sync"
"unsafe"
Expand All @@ -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"
Expand Down Expand Up @@ -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, &params)

Expand All @@ -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(&params.Blk)

for i := range params.Txs {
Expand All @@ -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(&params.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, &params.Rewards_stats, &feesRewards)
totalReward := uint256.NewInt(0)
for i := range params.Rewards_stats {
reward := st.DistributeRewards(&params.Rewards_stats[i], &dpos.FeesRewards{})
if reward != nil {
totalReward.Add(totalReward, reward)
}
}
st.EndBlock()
if totalReward != nil {
retval.TotalReward = totalReward.ToBig()
}
Expand Down
4 changes: 2 additions & 2 deletions taraxa/state/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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)
}
Expand Down
3 changes: 2 additions & 1 deletion taraxa/state/dpos/precompiled/dpos_contract.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
16 changes: 11 additions & 5 deletions taraxa/state/dpos/tests/dpos_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:])
Expand Down Expand Up @@ -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{}
Expand Down Expand Up @@ -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)
Expand All @@ -590,13 +594,15 @@ 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()
validator_owner := addr(idx)
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
}

Expand Down
5 changes: 3 additions & 2 deletions taraxa/state/dpos/tests/dpos_test_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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
}
Expand Down
4 changes: 2 additions & 2 deletions taraxa/state/internal/coin_trx_perftest/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -233,7 +233,7 @@ func main() {
}
st.ExecuteTransaction(&trx)
}
st.EndBlock(nil, nil, nil)
st.EndBlock()
})
with_timer("trie_commit", func() {
st.PrepareCommit()
Expand Down
3 changes: 1 addition & 2 deletions taraxa/state/internal/tests/eth_mainnet.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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())
Expand Down
13 changes: 6 additions & 7 deletions taraxa/state/rewards_stats/rewards_stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
kstdl marked this conversation as resolved.
Show resolved Hide resolved

// Total unique transactions counter
TotalDagBlocksCount uint32

Expand All @@ -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
}
2 changes: 1 addition & 1 deletion taraxa/state/state_transifiton_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
10 changes: 7 additions & 3 deletions taraxa/state/state_transition/state_transition.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down