Skip to content

Commit

Permalink
fix int64 overflow for height comparison
Browse files Browse the repository at this point in the history
  • Loading branch information
bluele committed Nov 16, 2020
1 parent 54201d1 commit 1c5604d
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
13 changes: 8 additions & 5 deletions x/ibc/core/02-client/types/height.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package types

import (
"fmt"
"math/big"
"regexp"
"strconv"
"strings"
Expand Down Expand Up @@ -54,15 +55,17 @@ 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 {
if r := a.Cmp(&b); r < 0 {
return -1
} else if cmp > 0 {
} else if r > 0 {
return 1
}
return 0
Expand Down
3 changes: 3 additions & 0 deletions x/ibc/core/02-client/types/height_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package types_test

import (
"math"
"testing"

"github.com/stretchr/testify/require"
Expand All @@ -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},
}

Expand Down

0 comments on commit 1c5604d

Please sign in to comment.