Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion types/address.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"crypto/sha512"
"encoding/base32"
"encoding/base64"
"fmt"
)

const (
Expand Down Expand Up @@ -64,7 +65,8 @@ func (a *Address) UnmarshalText(text []byte) error {
}

// DecodeAddress turns a checksum address string into an Address object. It
// checks that the checksum is correct, and returns an error if it's not.
// checks that the checksum is correct and whether the address is canonical,
// and returns an error if it's not.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

func DecodeAddress(addr string) (a Address, err error) {
// Interpret the address as base32
decoded, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(addr)
Expand Down Expand Up @@ -94,6 +96,13 @@ func DecodeAddress(addr string) (a Address, err error) {

// Checksum is good, copy address bytes into output
copy(a[:], addressBytes)

// Check if address is canonical
Copy link
Copy Markdown
Contributor Author

@algochoi algochoi Aug 21, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if a.String() != addr {
err = fmt.Errorf("address %s is non-canonical", addr)
return
}

return a, nil
}

Expand Down
15 changes: 15 additions & 0 deletions types/address_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,18 @@ func TestUnmarshalAddress(t *testing.T) {
})
}
}

func TestDecodeNonCanonicalAddress(t *testing.T) {
// Canonical addresses must end with one of the following: "AEIMQUY4",
// e.g. "7HJBGRIWI7GDL42SOJNIAZ7LJ7EBEGKGE5S52QZXAWDXOHDKMDFR6AUXDE"
addrs := []string{
"7HJBGRIWI7GDL42SOJNIAZ7LJ7EBEGKGE5S52QZXAWDXOHDKMDFR6AUXDF",
"7HJBGRIWI7GDL42SOJNIAZ7LJ7EBEGKGE5S52QZXAWDXOHDKMDFR6AUXDG",
"7HJBGRIWI7GDL42SOJNIAZ7LJ7EBEGKGE5S52QZXAWDXOHDKMDFR6AUXDH",
}
for _, addr := range addrs {
_, err := DecodeAddress(addr)
require.Error(t, err)
require.ErrorContains(t, err, fmt.Sprintf("address %s is non-canonical", addr))
}
}