Skip to content

Commit

Permalink
Merge pull request #1038 from maticnetwork/vaibhav/MilestoneIteration1
Browse files Browse the repository at this point in the history
Vaibhav/milestone iteration1
  • Loading branch information
VAIBHAVJINDAL3012 committed Aug 24, 2023
2 parents b84aac3 + 397b508 commit 8c16e6e
Show file tree
Hide file tree
Showing 13 changed files with 165 additions and 83 deletions.
6 changes: 6 additions & 0 deletions auth/ante.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (

authTypes "github.com/maticnetwork/heimdall/auth/types"
"github.com/maticnetwork/heimdall/chainmanager"
checkpointTypes "github.com/maticnetwork/heimdall/checkpoint/types"
"github.com/maticnetwork/heimdall/helper"
"github.com/maticnetwork/heimdall/types"
)
Expand Down Expand Up @@ -122,6 +123,11 @@ func NewAnteHandler(
}
}()

//Check whether the chain has reached the hard fork length to execute milestone msgs
if ctx.BlockHeight() <= helper.GetMilestoneHardForkHeight() && stdTx.Msg.Type() == checkpointTypes.EventTypeMilestone {
return newCtx, sdk.ErrUnknownRequest("Milestone msgs proposed before the hardfork").Result(), true
}

// validate tx
if err := tx.ValidateBasic(); err != nil {
return newCtx, err.Result(), true
Expand Down
53 changes: 53 additions & 0 deletions auth/ante_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,43 @@ func (suite *AnteTestSuite) TestFees() {
checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeInsufficientFunds)
}

func (suite *AnteTestSuite) TestMilestoneHardFork() {
t, happ, ctx, anteHandler := suite.T(), suite.app, suite.ctx, suite.anteHandler
ctx = ctx.WithBlockHeight(1)

// keys and addresses
priv1, _, addr1 := sdkAuth.KeyTestPubAddr()

// set the accounts
acc1 := happ.AccountKeeper.NewAccountWithAddress(ctx, hmTypes.AccAddressToHeimdallAddress(addr1))
amt1, _ := sdk.NewIntFromString(authTypes.DefaultTxFees)
err := acc1.SetCoins(sdk.NewCoins(sdk.NewCoin(authTypes.FeeToken, amt1)))
require.NoError(t, err)
happ.AccountKeeper.SetAccount(ctx, acc1)
acc1 = happ.AccountKeeper.GetAccount(ctx, acc1.GetAddress()) // get stored account

var tx sdk.Tx

// checkpoint msg
msg := TestMilestoneMsg{*sdkAuth.NewTestMsg(addr1)}

ctx = ctx.WithBlockHeight(int64(0))
// test good tx from one signer
tx = types.NewTestTx(ctx, sdk.Msg(&msg), priv1, acc1.GetAccountNumber(), uint64(0))
checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeUnknownRequest)

acc1 = happ.AccountKeeper.GetAccount(ctx, acc1.GetAddress())
require.Equal(t, amt1, (acc1.GetCoins()).AmountOf(authTypes.FeeToken))

ctx = ctx.WithBlockHeight(int64(1))

tx = types.NewTestTx(ctx, sdk.Msg(&msg), priv1, acc1.GetAccountNumber(), uint64(0))
checkValidTx(t, anteHandler, ctx, tx, false)

acc1 = happ.AccountKeeper.GetAccount(ctx, acc1.GetAddress())
require.NotEqual(t, amt1, (acc1.GetCoins()).AmountOf(authTypes.FeeToken))
}

//
// utils
//
Expand Down Expand Up @@ -456,3 +493,19 @@ type TestCheckpointMsg struct {

func (msg *TestCheckpointMsg) Route() string { return testCheckpointMsgVal }
func (msg *TestCheckpointMsg) Type() string { return testCheckpointMsgVal }

//
// Test checkpoint
//

const testMilestoneMsgVal = "milestone"

var _ sdk.Msg = (*TestMilestoneMsg)(nil)

// msg type for testing
type TestMilestoneMsg struct {
sdk.TestMsg
}

func (msg *TestMilestoneMsg) Route() string { return testMilestoneMsgVal }
func (msg *TestMilestoneMsg) Type() string { return testMilestoneMsgVal }
5 changes: 3 additions & 2 deletions chainmanager/types/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ import (

// Default parameter values
const (
DefaultMainchainTxConfirmations uint64 = 6
DefaultMaticchainTxConfirmations uint64 = 10
DefaultMainchainTxConfirmations uint64 = 6
DefaultMaticchainTxConfirmations uint64 = 10
DefaultMaticchainMilestoneTxConfirmations uint64 = 16
)

var (
Expand Down
18 changes: 12 additions & 6 deletions checkpoint/handler_milestone.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,6 @@ func handleMsgMilestone(ctx sdk.Context, msg types.MsgMilestone, k Keeper) sdk.R
logger := k.Logger(ctx)
milestoneLength := helper.MilestoneLength

//Check whether the chain has reached the hard fork length
if ctx.BlockHeight() < helper.GetMilestoneHardForkHeight() {
logger.Error("Network hasn't reached the", "Hard forked height", helper.GetMilestoneHardForkHeight())
return common.ErrInvalidMsg(k.Codespace(), "Network hasn't reached the milestone hard forked height").Result()
}

//
//Get milestone validator set
//
Expand All @@ -49,6 +43,16 @@ func handleMsgMilestone(ctx sdk.Context, msg types.MsgMilestone, k Keeper) sdk.R
return common.ErrInvalidMsg(k.Codespace(), "Invalid proposer in msg").Result()
}

if ctx.BlockHeight()-k.GetMilestoneBlockNumber(ctx) < 2 {
logger.Error(
"Previous milestone still in voting phase",
"previousMilestoneBlock", k.GetMilestoneBlockNumber(ctx),
"currentMilestoneBlock", ctx.BlockHeight(),
)

return common.ErrPrevMilestoneInVoting(k.Codespace()).Result()
}

//Increment the priority in the milestone validator set
k.sk.MilestoneIncrementAccum(ctx, 1)

Expand Down Expand Up @@ -86,6 +90,8 @@ func handleMsgMilestone(ctx sdk.Context, msg types.MsgMilestone, k Keeper) sdk.R
return common.ErrNoMilestoneFound(k.Codespace()).Result()
}

k.SetMilestoneBlockNumber(ctx, ctx.BlockHeight())

//Set the MilestoneID in the cache
types.SetMilestoneID(msg.MilestoneID)

Expand Down
86 changes: 50 additions & 36 deletions checkpoint/handler_milestone_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (

sdk "github.com/cosmos/cosmos-sdk/types"

cmTypes "github.com/maticnetwork/heimdall/chainmanager/types"
chSim "github.com/maticnetwork/heimdall/checkpoint/simulation"
"github.com/maticnetwork/heimdall/checkpoint/types"
errs "github.com/maticnetwork/heimdall/common"
Expand Down Expand Up @@ -44,11 +45,11 @@ func (suite *HandlerTestSuite) TestHandleMsgMilestone() {
header, err := chSim.GenRandMilestone(start, milestoneLength)
require.NoError(t, err)

// add current proposer to header
header.Proposer = stakingKeeper.GetMilestoneValidatorSet(ctx).Proposer.Signer
ctx = ctx.WithBlockHeight(3)

//Test1- When the milestone msg is sent before the hardfork value
suite.Run("Failure-Before Hard Fork", func() {
//Test1- When milestone is proposed by wrong proposer
suite.Run("Invalid Proposer", func() {
header.Proposer = hmTypes.HexToHeimdallAddress("1234")
msgMilestone := types.NewMsgMilestoneBlock(
header.Proposer,
header.StartBlock,
Expand All @@ -58,94 +59,104 @@ func (suite *HandlerTestSuite) TestHandleMsgMilestone() {
milestoneID,
)

ctxNew := ctx.WithBlockHeight(-1) //Setting height as -1 just to check for the hard fork.

// send milestone to handler
got := suite.handler(ctxNew, msgMilestone)
require.False(t, got.IsOK(), "expected send-milstone to get failed")
got := suite.handler(ctx, msgMilestone)
require.True(t, !got.IsOK(), errs.CodeToDefaultMsg(got.Code))
require.Equal(t, errs.CodeInvalidMsg, got.Code)
})

//Test2- When the first milestone is composed of incorrect start number
suite.Run("Failure-Invalid Start Block Number", func() {
// add current proposer to header
header.Proposer = stakingKeeper.GetMilestoneValidatorSet(ctx).Proposer.Signer

//Test2- When milestone is proposed of length shorter than configured minimum length
suite.Run("Invalid msg based on milestone length", func() {
msgMilestone := types.NewMsgMilestoneBlock(
header.Proposer,
uint64(1),
header.EndBlock+1,
header.StartBlock,
header.EndBlock-1,
header.Hash,
borChainId,
milestoneID,
)

// send milestone to handler
got := suite.handler(ctx, msgMilestone)
require.False(t, got.IsOK(), "expected send-milstone to be ok, got %v", got)
require.Equal(t, errs.CodeNoMilestone, got.Code)
require.True(t, !got.IsOK(), errs.CodeToDefaultMsg(got.Code))
require.Equal(t, errs.CodeMilestoneInvalid, got.Code)
})

//Test3- When milestone is proposed by wrong proposer
suite.Run("Invalid Proposer", func() {
header.Proposer = hmTypes.HexToHeimdallAddress("1234")
// add current proposer to header
header.Proposer = stakingKeeper.GetMilestoneValidatorSet(ctx).Proposer.Signer

//Test3- When the first milestone is composed of incorrect start number
suite.Run("Failure-Invalid Start Block Number", func() {
msgMilestone := types.NewMsgMilestoneBlock(
header.Proposer,
header.StartBlock,
header.EndBlock,
uint64(1),
header.EndBlock+1,
header.Hash,
borChainId,
milestoneID,
)

// send milestone to handler
got := suite.handler(ctx, msgMilestone)
require.True(t, !got.IsOK(), errs.CodeToDefaultMsg(got.Code))
require.Equal(t, errs.CodeInvalidMsg, got.Code)
require.False(t, got.IsOK(), "expected send-milstone to be ok, got %v", got)
require.Equal(t, errs.CodeNoMilestone, got.Code)
})

header.Proposer = stakingKeeper.GetMilestoneValidatorSet(ctx).Proposer.Signer

//Test4- When milestone is proposed of length shorter than configured minimum length
suite.Run("Invalid msg based on milestone length", func() {
//Test4- When the correct milestone is proposed
suite.Run("Success", func() {
msgMilestone := types.NewMsgMilestoneBlock(
header.Proposer,
header.StartBlock,
header.EndBlock-1,
header.EndBlock,
header.Hash,
borChainId,
milestoneID,
)

// send milestone to handler
got := suite.handler(ctx, msgMilestone)
require.True(t, !got.IsOK(), errs.CodeToDefaultMsg(got.Code))
require.Equal(t, errs.CodeMilestoneInvalid, got.Code)
require.True(t, got.IsOK(), "expected send-milstone to be ok, got %v", got)
bufferedHeader, _ := keeper.GetLastMilestone(ctx)
require.Empty(t, bufferedHeader, "Should not store state")
milestoneBlockNumber := keeper.GetMilestoneBlockNumber(ctx)
require.Equal(t, int64(3), milestoneBlockNumber, "Mismatch in milestoneBlockNumber")
})

header.Proposer = stakingKeeper.GetMilestoneValidatorSet(ctx).Proposer.Signer

//Test5- When the correct milestone is proposed
suite.Run("Success", func() {
ctx = ctx.WithBlockHeight(int64(4))

//Test5- When previous milestone is still in voting phase
suite.Run("Previous milestone is still in voting phase", func() {

msgMilestone := types.NewMsgMilestoneBlock(
header.Proposer,
header.StartBlock,
header.EndBlock,
start,
start+milestoneLength-1,
header.Hash,
borChainId,
milestoneID,
)

// send milestone to handler
got := suite.handler(ctx, msgMilestone)
require.True(t, got.IsOK(), "expected send-milstone to be ok, got %v", got)
bufferedHeader, _ := keeper.GetLastMilestone(ctx)
require.Empty(t, bufferedHeader, "Should not store state")
require.True(t, !got.IsOK(), errs.CodeToDefaultMsg(got.Code))
require.Equal(t, errs.CodePrevMilestoneInVoting, got.Code)
})

header.Proposer = stakingKeeper.GetMilestoneValidatorSet(ctx).Proposer.Signer

//Test6- When milestones are not in continuity
ctx = ctx.WithBlockHeight(int64(6))

//Test5- When milestone is not in continuity
suite.Run("Milestone not in countinuity", func() {

err = keeper.AddMilestone(ctx, header)
err := keeper.AddMilestone(ctx, header)
require.NoError(t, err)

_, err = keeper.GetLastMilestone(ctx)
Expand All @@ -170,11 +181,11 @@ func (suite *HandlerTestSuite) TestHandleMsgMilestone() {
got := suite.handler(ctx, msgMilestone)
require.True(t, !got.IsOK(), errs.CodeToDefaultMsg(got.Code))
require.Equal(t, errs.CodeMilestoneNotInContinuity, got.Code)

})

header.Proposer = stakingKeeper.GetMilestoneValidatorSet(ctx).Proposer.Signer

//Test6- When milestone is not in continuity
suite.Run("Milestone not in countinuity", func() {

_, err = keeper.GetLastMilestone(ctx)
Expand Down Expand Up @@ -254,9 +265,12 @@ func (suite *HandlerTestSuite) SendMilestone(header hmTypes.Milestone) (res sdk.
)

suite.contractCaller.On("CheckIfBlocksExist", header.EndBlock).Return(true)
suite.contractCaller.On("CheckIfBlocksExist", header.EndBlock+cmTypes.DefaultMaticchainMilestoneTxConfirmations).Return(true)
suite.contractCaller.On("GetRootHash", header.StartBlock, header.EndBlock, milestoneLength).Return(header.Hash.Bytes(), nil)
suite.contractCaller.On("GetVoteOnHash", header.StartBlock, header.EndBlock, milestoneLength, header.Hash.String(), header.MilestoneID).Return(true, nil)

ctx = ctx.WithBlockHeight(int64(3))

// send milestone to handler
result := suite.handler(ctx, msgMilestone)
sideResult := suite.sideHandler(ctx, msgMilestone)
Expand Down
25 changes: 25 additions & 0 deletions checkpoint/keeper_milestone.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ var (
MilestoneNoAckKey = []byte{0x40} //Key to store the NoAckMilestone
MilestoneLastNoAckKey = []byte{0x50} //Key to store the Latest NoAckMilestone
LastMilestoneTimeout = []byte{0x60} //Key to store the Last Milestone Timeout
BlockNumberKey = []byte{0x70} //Key to store the count
)

// AddMilestone adds milestone in the store
Expand Down Expand Up @@ -124,6 +125,30 @@ func (k *Keeper) GetMilestoneCount(ctx sdk.Context) uint64 {
return uint64(0)
}

// SetMilestoneBlockNumber set the block number when the latest milestone enter the handler
func (k *Keeper) SetMilestoneBlockNumber(ctx sdk.Context, number int64) {
store := ctx.KVStore(k.storeKey)
// convert block number to bytes
value := []byte(strconv.FormatInt(number, 10))
// set
store.Set(BlockNumberKey, value)
}

// GetMilestoneBlockNumber returns the block number when the latest milestone enter the handler
func (k *Keeper) GetMilestoneBlockNumber(ctx sdk.Context) int64 {
store := ctx.KVStore(k.storeKey)
// check if block number is there
if store.Has(BlockNumberKey) {
// get the block number
result, err := strconv.ParseInt(string(store.Get(BlockNumberKey)), 10, 64)
if err == nil {
return result
}
}

return int64(0)
}

// PruneMilestone remove the milestone from the db based on number
func (k *Keeper) PruneMilestone(ctx sdk.Context, number uint64) {
store := ctx.KVStore(k.storeKey)
Expand Down
3 changes: 2 additions & 1 deletion checkpoint/side_milestone_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
abci "github.com/tendermint/tendermint/abci/types"
tmTypes "github.com/tendermint/tendermint/types"

cmTypes "github.com/maticnetwork/heimdall/chainmanager/types"
"github.com/maticnetwork/heimdall/checkpoint/types"
"github.com/maticnetwork/heimdall/common"
"github.com/maticnetwork/heimdall/helper"
Expand Down Expand Up @@ -49,7 +50,7 @@ func SideHandleMsgMilestone(ctx sdk.Context, k Keeper, msg types.MsgMilestone, c
}

//Validating the milestone
validMilestone, err := types.ValidateMilestone(msg.StartBlock, msg.EndBlock, msg.Hash, msg.MilestoneID, contractCaller, milestoneLength)
validMilestone, err := types.ValidateMilestone(msg.StartBlock, msg.EndBlock, msg.Hash, msg.MilestoneID, contractCaller, milestoneLength, cmTypes.DefaultMaticchainMilestoneTxConfirmations)
if err != nil {
logger.Error("Error validating milestone",
"startBlock", msg.StartBlock,
Expand Down

0 comments on commit 8c16e6e

Please sign in to comment.