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>
This commit is contained in:
Jun Kimura 2020-11-17 19:42:06 +09:00 committed by GitHub
parent 2f6ebb7792
commit f962f3a28c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 10 additions and 9 deletions

View File

@ -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

View File

@ -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},
}