diff --git a/libs/bytes/bytes.go b/libs/bytes/bytes.go index 86d5d965e..3ca32e8ce 100644 --- a/libs/bytes/bytes.go +++ b/libs/bytes/bytes.go @@ -70,6 +70,8 @@ func (bz HexBytes) Format(s fmt.State, verb rune) { } } +// Matches the hexbytes MarshalJSON of tendermint/tendermint. Overrides the +// default []byte Marshal implementation. This is basically the point of hex bytes. func (bz HexBytes) MarshalJSON() ([]byte, error) { s := strings.ToUpper(hex.EncodeToString(bz)) jbz := make([]byte, len(s)+2) @@ -79,6 +81,8 @@ func (bz HexBytes) MarshalJSON() ([]byte, error) { return jbz, nil } +// Matches the hexbytes UnmarshalJSON of tendermint/tendermint. Overrides the +// default []byte Marshal implementation. This is basically the point of hex bytes. func (bz *HexBytes) UnmarshalJSON(data []byte) error { if len(data) < 2 || data[0] != '"' || data[len(data)-1] != '"' { return fmt.Errorf("invalid hex string: %s", data) diff --git a/libs/bytes/bytes_test.go b/libs/bytes/bytes_test.go index fb1200a04..3dcd08100 100644 --- a/libs/bytes/bytes_test.go +++ b/libs/bytes/bytes_test.go @@ -72,3 +72,41 @@ func TestHexBytes_String(t *testing.T) { t.Fatal(err) } } + +// Define a struct to match the JSON structure +type ValidatorsHash struct { + NextValidatorsHash HexBytes `json:"next_validators_hash"` +} + +func TestMarshalBasic(t *testing.T) { + var vh ValidatorsHash + vh.NextValidatorsHash = []byte("abc") + bz, err := json.Marshal(vh) + if err != nil { + t.Fatal(err) + } + assert.Equal(t, string(bz), "{\"next_validators_hash\":\"616263\"}") +} + +func TestUnmarshalBasic(t *testing.T) { + jsonData := []byte(`{"next_validators_hash":"616263"}`) + var vh ValidatorsHash + err := json.Unmarshal(jsonData, &vh) + if err != nil { + t.Fatalf("Error unmarshalling JSON: %v", err) + return + } + assert.Equal(t, string(vh.NextValidatorsHash), "abc") +} + +func TestUnmarshalExample(t *testing.T) { + jsonData := []byte(`{"next_validators_hash":"20021C2FB4B2DDFF6E8C484A2ED5862910E3AD7074FC6AD1C972AD34891AE3A4"}`) + expectedLength := 32 + var vh ValidatorsHash + err := json.Unmarshal(jsonData, &vh) + if err != nil { + t.Fatalf("Error unmarshalling JSON: %v", err) + return + } + assert.Equal(t, expectedLength, len(vh.NextValidatorsHash)) +}