From f962f3a28c3b91cf79ee31891d9235e65e3b8513 Mon Sep 17 00:00:00 2001 From: Jun Kimura Date: Tue, 17 Nov 2020 19:42:06 +0900 Subject: [PATCH] Fix int64 overflow error for height comparison (#7944) * fix int64 overflow for height comparison * apply suggestions from review Co-authored-by: Federico Kunze <31522760+fedekunze@users.noreply.github.com> --- x/ibc/core/02-client/types/height.go | 16 +++++++--------- x/ibc/core/02-client/types/height_test.go | 3 +++ 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/x/ibc/core/02-client/types/height.go b/x/ibc/core/02-client/types/height.go index 72af4d56b2..ab156e80de 100644 --- a/x/ibc/core/02-client/types/height.go +++ b/x/ibc/core/02-client/types/height.go @@ -2,6 +2,7 @@ package types import ( "fmt" + "math/big" "regexp" "strconv" "strings" @@ -54,18 +55,15 @@ func (h Height) Compare(other exported.Height) int64 { if !ok { panic(fmt.Sprintf("cannot compare against invalid height type: %T. expected height type: %T", other, h)) } - var cmp int64 + var a, b big.Int if h.VersionNumber != height.VersionNumber { - cmp = int64(h.VersionNumber) - int64(height.VersionNumber) + a.SetUint64(h.VersionNumber) + b.SetUint64(height.VersionNumber) } else { - cmp = int64(h.VersionHeight) - int64(height.VersionHeight) + a.SetUint64(h.VersionHeight) + b.SetUint64(height.VersionHeight) } - if cmp < 0 { - return -1 - } else if cmp > 0 { - return 1 - } - return 0 + return int64(a.Cmp(&b)) } // LT Helper comparison function returns true if h < other diff --git a/x/ibc/core/02-client/types/height_test.go b/x/ibc/core/02-client/types/height_test.go index 33d33fd714..0bd8f0848f 100644 --- a/x/ibc/core/02-client/types/height_test.go +++ b/x/ibc/core/02-client/types/height_test.go @@ -1,6 +1,7 @@ package types_test import ( + "math" "testing" "github.com/stretchr/testify/require" @@ -23,6 +24,8 @@ func TestCompareHeights(t *testing.T) { {"version number 1 is greater", types.NewHeight(7, 5), types.NewHeight(4, 5), 1}, {"version height 1 is lesser", types.NewHeight(3, 4), types.NewHeight(3, 9), -1}, {"version height 1 is greater", types.NewHeight(3, 8), types.NewHeight(3, 3), 1}, + {"version number is MaxUint64", types.NewHeight(math.MaxUint64, 1), types.NewHeight(0, 1), 1}, + {"version height is MaxUint64", types.NewHeight(1, math.MaxUint64), types.NewHeight(1, 0), 1}, {"height is equal", types.NewHeight(4, 4), types.NewHeight(4, 4), 0}, }