From e1512c52e98d5d51cb76e366b9865062066d14f9 Mon Sep 17 00:00:00 2001 From: Loredana Cirstea Date: Thu, 7 Apr 2022 13:51:28 +0300 Subject: [PATCH] types: add `ValidateNonZeroAddress` utility function (#1033) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add ValidateNonZeroAddress validation utility * Update types/validation.go Co-authored-by: Federico Kunze Küllmer <31522760+fedekunze@users.noreply.github.com> --- types/validation.go | 12 ++++++++++++ types/validation_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/types/validation.go b/types/validation.go index 15e27ee3..084246f5 100644 --- a/types/validation.go +++ b/types/validation.go @@ -29,6 +29,18 @@ func ValidateAddress(address string) error { return nil } +// ValidateNonZeroAddress returns an error if the provided string is not a hex +// formatted string address or is equal to zero +func ValidateNonZeroAddress(address string) error { + if IsZeroAddress(address) { + return sdkerrors.Wrapf( + sdkerrors.ErrInvalidAddress, "address '%s' must not be zero", + address, + ) + } + return ValidateAddress(address) +} + // SafeInt64 checks for overflows while casting a uint64 to int64 value. func SafeInt64(value uint64) (int64, error) { if value > uint64(math.MaxInt64) { diff --git a/types/validation_test.go b/types/validation_test.go index 86e387d4..ee60a19f 100644 --- a/types/validation_test.go +++ b/types/validation_test.go @@ -85,6 +85,37 @@ func TestValidateAddress(t *testing.T) { } } +func TestValidateNonZeroAddress(t *testing.T) { + testCases := []struct { + name string + address string + expError bool + }{ + { + "empty string", "", true, + }, + { + "invalid address", "0x", true, + }, + { + "zero address", common.Address{}.String(), true, + }, + { + "valid address", tests.GenerateAddress().Hex(), false, + }, + } + + for _, tc := range testCases { + err := ValidateNonZeroAddress(tc.address) + + if tc.expError { + require.Error(t, err, tc.name) + } else { + require.NoError(t, err, tc.name) + } + } +} + func TestSafeInt64(t *testing.T) { testCases := []struct { name string