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

ehancement(Bytes32): apply left hand padding in UnmarshalJSON #867

Closed
wants to merge 2 commits into from
Closed
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
17 changes: 8 additions & 9 deletions thor/bytes32.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ package thor
import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"strings"

Expand Down Expand Up @@ -65,14 +64,14 @@ func (b *Bytes32) UnmarshalJSON(data []byte) error {

// ParseBytes32 convert string presented into Bytes32 type
func ParseBytes32(s string) (Bytes32, error) {
if len(s) == 32*2 {
} else if len(s) == 32*2+2 {
if strings.ToLower(s[:2]) != "0x" {
return Bytes32{}, errors.New("invalid prefix")
}
s = s[2:]
} else {
return Bytes32{}, errors.New("invalid length")
s = strings.TrimPrefix(s, "0x")
// if the string is too long, return error
if len(s) > 32*2 {
return Bytes32{}, fmt.Errorf("invalid length %d", len(s))
}
// if the string is too short, add padding
if len(s) < 32*2 {
s = strings.Repeat("0", 32*2-len(s)) + s
}

var b Bytes32
Expand Down
11 changes: 10 additions & 1 deletion thor/bytes32_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"github.com/stretchr/testify/assert"
)

func TestMarshalUnmarshal(t *testing.T) {
func TestBytes32_UnmarshalJSON(t *testing.T) {
// Example hex string representing the value 100
originalHex := `"0x00000000000000000000000000000000000000000000000000006d6173746572"` // Note the enclosing double quotes for valid JSON string

Expand Down Expand Up @@ -50,3 +50,12 @@ func TestMarshalUnmarshal(t *testing.T) {
assert.NoError(t, err, "Marshaling should not produce an error")
assert.Equal(t, `"0x0000000000000000000000000000000000000000000000000000000000000000"`, string(j))
}

func TestParseBytes32(t *testing.T) {
// Example hex string representing the value 100
expected := MustParseBytes32("0x0000000000000000000000006d95e6dca01d109882fe1726a2fb9865fa41e7aa")
trimmed := "0x6d95e6dca01d109882fe1726a2fb9865fa41e7aa"
parsed, err := ParseBytes32(trimmed)
assert.NoError(t, err)
assert.Equal(t, expected, parsed)
}
Loading