From 4d3afea7ab7126742c6fbdedc2e5d941fd05d603 Mon Sep 17 00:00:00 2001 From: Federico Kunze <31522760+fedekunze@users.noreply.github.com> Date: Thu, 20 Aug 2020 12:22:13 +0200 Subject: [PATCH] launchpad: backport BigInt fix (#7087) Backported from #7084 Co-authored-by: Alessio Treglia --- CHANGELOG.md | 6 ++++++ types/decimal.go | 10 ++++++++++ types/int.go | 8 ++++++++ types/int_test.go | 2 ++ 4 files changed, 26 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index dadcf175e0ef..54eb0a126939 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,12 @@ Ref: https://keepachangelog.com/en/1.0.0/ # Changelog +## [v0.39.2] + +### Bug Fixes + +* (types) [\#7084](https://github.com/cosmos/cosmos-sdk/pull/7084) Fix panic when calling `BigInt()` on an uninitialized `Int`. + ## [v0.39.1] * (x/auth) [\#6861](https://github.com/cosmos/cosmos-sdk/pull/6861) Remove public key Bech32 encoding for all account types for JSON serialization, instead relying on direct Amino encoding. In addition, JSON serialization utilizes Amino instead of the Go stdlib, so integers are treated as strings. diff --git a/types/decimal.go b/types/decimal.go index 839523080656..03e27fc356d4 100644 --- a/types/decimal.go +++ b/types/decimal.go @@ -205,6 +205,16 @@ func (d Dec) LTE(d2 Dec) bool { return (d.Int).Cmp(d2.Int) <= 0 } // less func (d Dec) Neg() Dec { return Dec{new(big.Int).Neg(d.Int)} } // reverse the decimal sign func (d Dec) Abs() Dec { return Dec{new(big.Int).Abs(d.Int)} } // absolute value +// BigInt returns a copy of the underlying big.Int. +func (d Dec) BigInt() *big.Int { + if d.IsNil() { + return nil + } + + copy := new(big.Int) + return copy.Set(d.Int) +} + // addition func (d Dec) Add(d2 Dec) Dec { res := new(big.Int).Add(d.Int, d2.Int) diff --git a/types/int.go b/types/int.go index 0029dfaa4eb4..5d15d069ad17 100644 --- a/types/int.go +++ b/types/int.go @@ -106,9 +106,17 @@ type Int struct { // BigInt converts Int to big.Int func (i Int) BigInt() *big.Int { + if i.IsNil() { + return nil + } return new(big.Int).Set(i.i) } +// IsNil returns true if Int is uninitialized +func (i Int) IsNil() bool { + return i.i == nil +} + // NewInt constructs Int from int64 func NewInt(n int64) Int { return Int{big.NewInt(n)} diff --git a/types/int_test.go b/types/int_test.go index 072b2f47bb9a..d23985467cdf 100644 --- a/types/int_test.go +++ b/types/int_test.go @@ -78,6 +78,8 @@ func TestIntPanic(t *testing.T) { // Division-by-zero check require.Panics(t, func() { i1.Quo(NewInt(0)) }) + + require.NotPanics(t, func() { Int{}.BigInt() }) } // Tests below uses randomness