fix: math: add LegacyNewDecFromStr fuzzers + remove unnecessary error wrapping (#14252)

This commit is contained in:
Emmanuel T Odeke 2022-12-11 09:02:51 +00:00 committed by GitHub
parent b9511b9205
commit d247e7a3b0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 6 deletions

View File

@ -143,19 +143,15 @@ func LegacyNewDecFromIntWithPrec(i Int, prec int64) LegacyDec {
//
// CONTRACT - This function does not mutate the input str.
func LegacyNewDecFromStr(str string) (LegacyDec, error) {
if len(str) == 0 {
return LegacyDec{}, fmt.Errorf("%s: %w", str, ErrLegacyEmptyDecimalStr)
}
// first extract any negative symbol
neg := false
if str[0] == '-' {
if len(str) > 0 && str[0] == '-' {
neg = true
str = str[1:]
}
if len(str) == 0 {
return LegacyDec{}, fmt.Errorf("%s: %w", str, ErrLegacyEmptyDecimalStr)
return LegacyDec{}, ErrLegacyEmptyDecimalStr
}
strs := strings.Split(str, ".")

30
math/fuzz_test.go Normal file
View File

@ -0,0 +1,30 @@
package math
import (
"testing"
)
func FuzzLegacyNewDecFromStr(f *testing.F) {
if testing.Short() {
f.Skip("running in -short mode")
}
f.Add("-123.456")
f.Add("123.456789")
f.Add("123456789")
f.Add("0.12123456789")
f.Add("-12123456789")
f.Fuzz(func(t *testing.T, input string) {
dec, err := LegacyNewDecFromStr(input)
if err != nil && !dec.IsNil() {
t.Fatalf("Inconsistency: dec.notNil=%v yet err=%v", dec, err)
}
})
}
func TestDecNegativePrecision(t *testing.T) {
t.Skip("https://github.com/cosmos/cosmos-sdk/issues/14004 is not yet addressed")
LegacyNewDecWithPrec(10, -1)
}