Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

clean up ethtypes: rationalize ethtypes.EthAddressFromFilecoinAddress and conversion methods #9992

Merged
merged 5 commits into from
Jan 12, 2023
Merged
Changes from 1 commit
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
27 changes: 11 additions & 16 deletions chain/types/ethtypes/eth_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,6 @@ func EthAddressFromFilecoinAddress(addr address.Address) (EthAddress, error) {

// ParseEthAddress parses an Ethereum address from a hex string.
func ParseEthAddress(s string) (EthAddress, error) {
handlePrefix(&s)
b, err := decodeHexString(s, EthAddressLength)
if err != nil {
return EthAddress{}, err
Expand Down Expand Up @@ -372,25 +371,22 @@ func (h *EthHash) UnmarshalJSON(b []byte) error {
return nil
}

func handlePrefix(s *string) {
if strings.HasPrefix(*s, "0x") || strings.HasPrefix(*s, "0X") {
*s = (*s)[2:]
func decodeHexString(s string, expectedLen int) ([]byte, error) {
// Strip the leading 0x or 0X prefix since hex.DecodeString does not support it.
if strings.HasPrefix(s, "0x") || strings.HasPrefix(s, "0X") {
s = s[2:]
}
if len(*s)%2 == 1 {
*s = "0" + *s
// Sometimes clients will omit a leading zero in a byte; pad so we can decode correctly.
if len(s)%2 == 1 {
s = "0" + s
}
if len(s) != expectedLen*2 {
return []byte{}, xerrors.Errorf("expected length %d, got %d", expectedLen, len(s))
Copy link
Contributor

Choose a reason for hiding this comment

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

Is returning nil not more canonical here?

Copy link
Member Author

Choose a reason for hiding this comment

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

Yep, can do. I'm working on another fix that affects this code, so will do in the next PR.

}
}

func decodeHexString(s string, length int) ([]byte, error) {
b, err := hex.DecodeString(s)
if err != nil {
return []byte{}, xerrors.Errorf("cannot parse hash: %w", err)
}

if len(b) > length {
return []byte{}, xerrors.Errorf("length of decoded bytes is longer than %d", length)
return []byte{}, xerrors.Errorf("cannot parse hex value: %w", err)
}

return b, nil
}

Expand All @@ -399,7 +395,6 @@ func EthHashFromCid(c cid.Cid) (EthHash, error) {
}

func ParseEthHash(s string) (EthHash, error) {
handlePrefix(&s)
b, err := decodeHexString(s, EthHashLength)
if err != nil {
return EthHash{}, err
Expand Down