Skip to content

Commit

Permalink
refactor: Optimised number of GetBlockNumber and GetStakerId eth …
Browse files Browse the repository at this point in the history
…calls (#1204)

* refactor: Used getStakerId() only once

* refactor: used exisiting blockNumber from Vote() in dependent functions

* refactor: fixed tests after header being passed as a parameter

* fix: removed continous retries if error in fetching block number in logger

* refactor: added tests when context is cancelled for Vote()

* refactor: fixed vote tests
  • Loading branch information
Yashk767 authored Apr 30, 2024
1 parent 971f94a commit 2a341b2
Show file tree
Hide file tree
Showing 17 changed files with 295 additions and 212 deletions.
4 changes: 2 additions & 2 deletions block/block.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ func CalculateLatestBlock(client *ethclient.Client) {
latestHeader, err := client.HeaderByNumber(context.Background(), nil)
if err != nil {
logrus.Error("CalculateBlockNumber: Error in fetching block: ", err)
continue
} else {
SetLatestBlock(latestHeader)
}
SetLatestBlock(latestHeader)
}
time.Sleep(time.Second * time.Duration(core.BlockNumberInterval))
}
Expand Down
7 changes: 6 additions & 1 deletion cmd/cmd-utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@ func (*UtilsStruct) GetEpochAndState(client *ethclient.Client) (uint32, int64, e
if err != nil {
return 0, 0, err
}
state, err := razorUtils.GetBufferedState(client, bufferPercent)
latestHeader, err := clientUtils.GetLatestBlockWithRetry(client)
if err != nil {
log.Error("Error in fetching block: ", err)
return 0, 0, err
}
state, err := razorUtils.GetBufferedState(client, latestHeader, bufferPercent)
if err != nil {
return 0, 0, err
}
Expand Down
23 changes: 22 additions & 1 deletion cmd/cmd-utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cmd

import (
"errors"
Types "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/spf13/pflag"
"github.com/stretchr/testify/mock"
Expand All @@ -15,6 +16,8 @@ func TestGetEpochAndState(t *testing.T) {
type args struct {
epoch uint32
epochErr error
latestHeader *Types.Header
latestHeaderErr error
bufferPercent int32
bufferPercentErr error
state int64
Expand All @@ -32,6 +35,7 @@ func TestGetEpochAndState(t *testing.T) {
name: "Test 1: When GetEpochAndState function executes successfully",
args: args{
epoch: 4,
latestHeader: &Types.Header{},
bufferPercent: 20,
state: 0,
stateName: "commit",
Expand All @@ -44,6 +48,7 @@ func TestGetEpochAndState(t *testing.T) {
name: "Test 2: When there is an error in getting epoch",
args: args{
epochErr: errors.New("epoch error"),
latestHeader: &Types.Header{},
bufferPercent: 20,
state: 0,
stateName: "commit",
Expand All @@ -56,6 +61,7 @@ func TestGetEpochAndState(t *testing.T) {
name: "Test 3: When there is an error in getting bufferPercent",
args: args{
epoch: 4,
latestHeader: &Types.Header{},
bufferPercentErr: errors.New("bufferPercent error"),
state: 0,
stateName: "commit",
Expand All @@ -68,21 +74,36 @@ func TestGetEpochAndState(t *testing.T) {
name: "Test 4: When there is an error in getting state",
args: args{
epoch: 4,
latestHeader: &Types.Header{},
bufferPercent: 20,
stateErr: errors.New("state error"),
},
wantEpoch: 0,
wantState: 0,
wantErr: errors.New("state error"),
},
{
name: "Test 5: When there is an error in getting latest header",
args: args{
epoch: 4,
latestHeaderErr: errors.New("header error"),
bufferPercent: 20,
state: 0,
stateName: "commit",
},
wantEpoch: 0,
wantState: 0,
wantErr: errors.New("header error"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
SetUpMockInterfaces()

utilsMock.On("GetEpoch", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.epoch, tt.args.epochErr)
cmdUtilsMock.On("GetBufferPercent").Return(tt.args.bufferPercent, tt.args.bufferPercentErr)
utilsMock.On("GetBufferedState", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("int32")).Return(tt.args.state, tt.args.stateErr)
clientUtilsMock.On("GetLatestBlockWithRetry", mock.Anything).Return(tt.args.latestHeader, tt.args.latestHeaderErr)
utilsMock.On("GetBufferedState", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.state, tt.args.stateErr)

utils := &UtilsStruct{}
gotEpoch, gotState, err := utils.GetEpochAndState(client)
Expand Down
5 changes: 3 additions & 2 deletions cmd/commit.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package cmd
import (
"encoding/hex"
"errors"
Types "github.com/ethereum/go-ethereum/core/types"
"math/big"
"razor/cache"
"razor/client"
Expand Down Expand Up @@ -150,8 +151,8 @@ func (*UtilsStruct) HandleCommitState(client *ethclient.Client, epoch uint32, se
/*
Commit finally commits the data to the smart contract. It calculates the commitment to send using the merkle tree root and the seed.
*/
func (*UtilsStruct) Commit(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, seed []byte, values []*big.Int) (common.Hash, error) {
if state, err := razorUtils.GetBufferedState(client, config.BufferPercent); err != nil || state != 0 {
func (*UtilsStruct) Commit(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, latestHeader *Types.Header, seed []byte, values []*big.Int) (common.Hash, error) {
if state, err := razorUtils.GetBufferedState(client, latestHeader, config.BufferPercent); err != nil || state != 0 {
log.Error("Not commit state")
return core.NilHash, err
}
Expand Down
15 changes: 8 additions & 7 deletions cmd/commit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,12 @@ import (

func TestCommit(t *testing.T) {
var (
client *ethclient.Client
account types.Account
config types.Configurations
seed []byte
epoch uint32
client *ethclient.Client
account types.Account
config types.Configurations
latestHeader *Types.Header
seed []byte
epoch uint32
)

type args struct {
Expand Down Expand Up @@ -95,13 +96,13 @@ func TestCommit(t *testing.T) {
utils.MerkleInterface = &utils.MerkleTreeStruct{}
merkleUtils = utils.MerkleInterface

utilsMock.On("GetBufferedState", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("int32")).Return(tt.args.state, tt.args.stateErr)
utilsMock.On("GetBufferedState", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(tt.args.state, tt.args.stateErr)
utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(TxnOpts)
voteManagerMock.On("Commit", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts"), mock.AnythingOfType("uint32"), mock.Anything).Return(tt.args.commitTxn, tt.args.commitErr)
transactionMock.On("Hash", mock.AnythingOfType("*types.Transaction")).Return(tt.args.hash)

utils := &UtilsStruct{}
got, err := utils.Commit(client, config, account, epoch, seed, tt.args.values)
got, err := utils.Commit(client, config, account, epoch, latestHeader, seed, tt.args.values)
if got != tt.want {
t.Errorf("Txn hash for Commit function, got = %v, want = %v", got, tt.want)
}
Expand Down
16 changes: 8 additions & 8 deletions cmd/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,13 +166,13 @@ type UtilsCmdInterface interface {
ClaimBlockReward(options types.TransactionOptions) (common.Hash, error)
GetSalt(client *ethclient.Client, epoch uint32) ([32]byte, error)
HandleCommitState(client *ethclient.Client, epoch uint32, seed []byte, httpClient *client.HttpClient, rogueData types.Rogue) (types.CommitData, error)
Commit(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, seed []byte, values []*big.Int) (common.Hash, error)
Commit(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, latestHeader *Types.Header, seed []byte, values []*big.Int) (common.Hash, error)
ListAccounts() ([]accounts.Account, error)
AssignAmountInWei(flagSet *pflag.FlagSet) (*big.Int, error)
ExecuteTransfer(flagSet *pflag.FlagSet)
Transfer(client *ethclient.Client, config types.Configurations, transferInput types.TransferInput) (common.Hash, error)
CheckForLastCommitted(client *ethclient.Client, staker bindings.StructsStaker, epoch uint32) error
Reveal(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, commitData types.CommitData, signature []byte) (common.Hash, error)
Reveal(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, latestHeader *Types.Header, commitData types.CommitData, signature []byte) (common.Hash, error)
GenerateTreeRevealData(merkleTree [][][]byte, commitData types.CommitData) bindings.StructsMerkleTree
IndexRevealEventsOfCurrentEpoch(client *ethclient.Client, blockNumber *big.Int, epoch uint32) ([]types.RevealedStruct, error)
ExecuteCreateJob(flagSet *pflag.FlagSet)
Expand Down Expand Up @@ -207,7 +207,7 @@ type UtilsCmdInterface interface {
IsElectedProposer(proposer types.ElectedProposer, currentStakerStake *big.Int) bool
GetSortedRevealedValues(client *ethclient.Client, blockNumber *big.Int, epoch uint32) (*types.RevealedDataMaps, error)
GetIteration(client *ethclient.Client, proposer types.ElectedProposer, bufferPercent int32) int
Propose(client *ethclient.Client, config types.Configurations, account types.Account, staker bindings.StructsStaker, epoch uint32, blockNumber *big.Int, rogueData types.Rogue) error
Propose(client *ethclient.Client, config types.Configurations, account types.Account, staker bindings.StructsStaker, epoch uint32, latestHeader *Types.Header, rogueData types.Rogue) error
GiveSorted(client *ethclient.Client, blockManager *bindings.BlockManager, txnArgs types.TransactionOptions, epoch uint32, assetId uint16, sortedStakers []*big.Int) error
GetLocalMediansData(client *ethclient.Client, account types.Account, epoch uint32, blockNumber *big.Int, rogueData types.Rogue) (types.ProposeFileData, error)
CheckDisputeForIds(client *ethclient.Client, transactionOpts types.TransactionOptions, epoch uint32, blockIndex uint8, idsInProposedBlock []uint16, revealedCollectionIds []uint16) (*Types.Transaction, error)
Expand All @@ -232,16 +232,16 @@ type UtilsCmdInterface interface {
GetSmallestStakeAndId(client *ethclient.Client, epoch uint32) (*big.Int, uint32, error)
StakeCoins(txnArgs types.TransactionOptions) (common.Hash, error)
CalculateSecret(account types.Account, epoch uint32, keystorePath string, chainId *big.Int) ([]byte, []byte, error)
HandleBlock(client *ethclient.Client, account types.Account, blockNumber *big.Int, config types.Configurations, httpClient *client.HttpClient, rogueData types.Rogue, backupNodeActionsToIgnore []string)
HandleBlock(client *ethclient.Client, account types.Account, stakerId uint32, header *Types.Header, config types.Configurations, httpClient *client.HttpClient, rogueData types.Rogue, backupNodeActionsToIgnore []string)
ExecuteVote(flagSet *pflag.FlagSet)
Vote(ctx context.Context, config types.Configurations, client *ethclient.Client, account types.Account, httpClient *client.HttpClient, rogueData types.Rogue, backupNodeActionsToIgnore []string) error
Vote(ctx context.Context, config types.Configurations, client *ethclient.Client, account types.Account, stakerId uint32, httpClient *client.HttpClient, rogueData types.Rogue, backupNodeActionsToIgnore []string) error
HandleExit()
ExecuteListAccounts(flagSet *pflag.FlagSet)
ClaimCommission(flagSet *pflag.FlagSet)
ExecuteStake(flagSet *pflag.FlagSet)
InitiateCommit(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, stakerId uint32, httpClient *client.HttpClient, rogueData types.Rogue) error
InitiateReveal(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, staker bindings.StructsStaker, rogueData types.Rogue) error
InitiatePropose(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, staker bindings.StructsStaker, blockNumber *big.Int, rogueData types.Rogue) error
InitiateCommit(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, stakerId uint32, latestHeader *Types.Header, httpClient *client.HttpClient, rogueData types.Rogue) error
InitiateReveal(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, staker bindings.StructsStaker, latestHeader *Types.Header, rogueData types.Rogue) error
InitiatePropose(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, staker bindings.StructsStaker, latestHeader *Types.Header, rogueData types.Rogue) error
GetBountyIdFromEvents(client *ethclient.Client, blockNumber *big.Int, bountyHunter string) (uint32, error)
HandleClaimBounty(client *ethclient.Client, config types.Configurations, account types.Account) error
ExecuteContractAddresses(flagSet *pflag.FlagSet)
Expand Down
Loading

0 comments on commit 2a341b2

Please sign in to comment.