From bed952022b1147a356e3580592bb1e0a07051299 Mon Sep 17 00:00:00 2001 From: Marko Date: Mon, 20 Nov 2023 11:28:15 +0100 Subject: [PATCH] fix(math): preventative ciel call (#18519) --- math/CHANGELOG.md | 4 ++++ math/dec.go | 4 ++++ math/dec_test.go | 8 ++++++++ 3 files changed, 16 insertions(+) diff --git a/math/CHANGELOG.md b/math/CHANGELOG.md index 585006ea2a..e385c915a0 100644 --- a/math/CHANGELOG.md +++ b/math/CHANGELOG.md @@ -40,6 +40,10 @@ Ref: https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.j * [#18421](https://github.com/cosmos/cosmos-sdk/pull/18421) Add mutative api for `LegacyDec.BigInt()`. +### Bug Fixes + +* [#18519](https://github.com/cosmos/cosmos-sdk/pull/18519) Prevent Overflow in `Dec.Ceil()`. + ## [math/v1.2.0](https://github.com/cosmos/cosmos-sdk/releases/tag/math/v1.2.0) - 2023-11-07 ### Features diff --git a/math/dec.go b/math/dec.go index 1cff954936..4de74b0b37 100644 --- a/math/dec.go +++ b/math/dec.go @@ -742,6 +742,10 @@ func (d LegacyDec) Ceil() LegacyDec { return LegacyNewDecFromBigInt(quo) } + if d.i.BitLen() >= maxDecBitLen { + panic("Int overflow") + } + return LegacyNewDecFromBigInt(quo.Add(quo, oneInt)) } diff --git a/math/dec_test.go b/math/dec_test.go index 45cec78ae1..96d7231a94 100644 --- a/math/dec_test.go +++ b/math/dec_test.go @@ -408,6 +408,14 @@ func (s *decimalTestSuite) TestDecCeil() { } } +func (s *decimalTestSuite) TestCeilOverflow() { + d, err := math.LegacyNewDecFromStr("66749594872528440074844428317798503581334516323645399060845050244444366430645.000000000000000001") + s.Require().NoError(err) + s.Require().True(d.BigInt().BitLen() <= 315, "d is too large") + // this call panics because the value is too large + s.Require().Panics(func() { d.Ceil() }, "Ceil should panic on overflow") +} + func (s *decimalTestSuite) TestPower() { testCases := []struct { input math.LegacyDec