diff --git a/pkg/ethtypes/hexbytes.go b/pkg/ethtypes/hexbytes.go index 8b7ac2ef..c2d8fbfc 100644 --- a/pkg/ethtypes/hexbytes.go +++ b/pkg/ethtypes/hexbytes.go @@ -1,4 +1,4 @@ -// Copyright © 2022 Kaleido, Inc. +// Copyright © 2024 Kaleido, Inc. // // SPDX-License-Identifier: Apache-2.0 // @@ -62,6 +62,14 @@ func (h HexBytes0xPrefix) MarshalJSON() ([]byte, error) { return []byte(fmt.Sprintf(`"%s"`, h.String())), nil } +func (h HexBytes0xPrefix) Truncate(length int) HexBytes0xPrefix { + if length > len(h) { + return h + } + + return h[:length] +} + func NewHexBytes0xPrefix(s string) (HexBytes0xPrefix, error) { h, err := hex.DecodeString(strings.TrimPrefix(s, "0x")) if err != nil { diff --git a/pkg/ethtypes/hexbytes_test.go b/pkg/ethtypes/hexbytes_test.go index a3f939ce..5c406bdf 100644 --- a/pkg/ethtypes/hexbytes_test.go +++ b/pkg/ethtypes/hexbytes_test.go @@ -90,3 +90,38 @@ func TestHexByteConstructors(t *testing.T) { MustNewHexBytes0xPrefix("!wrong") }) } + +func TestHexBytesTruncation(t *testing.T) { + testStruct := struct { + H1 HexBytes0xPrefix `json:"h1"` + H2 HexBytes0xPrefix `json:"h2"` + H3 HexBytes0xPrefix `json:"h3"` + H4 HexBytes0xPrefix `json:"h4"` + }{} + + testData := `{ + "h1": "0x34d2e4fef9de99a2688148de11174741d1399992f261dcd6ff019211a91eda748dcef26338e992f4df60b8dee3fdd28a", + "h2": "0x34d2e4fef9de99a2688148de11174741d1399992f261dcd6ff019211a91eda74", + "h3": "0x34d2e4fef9", + "h4": "0x34d2e4fef9de99a2688148de11174741d1399992f261dcd6ff019211a91eda748dcef26338e992" + }` + + err := json.Unmarshal([]byte(testData), &testStruct) + assert.NoError(t, err) + + result := testStruct.H1.Truncate(32) + testStruct.H1 = result + + result = testStruct.H2.Truncate(32) + testStruct.H2 = result + + result = testStruct.H3.Truncate(32) + + result = testStruct.H4.Truncate(32) + testStruct.H4 = result + + assert.Equal(t, "0x34d2e4fef9de99a2688148de11174741d1399992f261dcd6ff019211a91eda74", testStruct.H1.String()) + assert.Equal(t, "0x34d2e4fef9de99a2688148de11174741d1399992f261dcd6ff019211a91eda74", testStruct.H2.String()) + assert.Equal(t, "0x34d2e4fef9", testStruct.H3.String()) + assert.Equal(t, "0x34d2e4fef9de99a2688148de11174741d1399992f261dcd6ff019211a91eda74", testStruct.H4.String()) +} diff --git a/pkg/ethtypes/hexinteger_test.go b/pkg/ethtypes/hexinteger_test.go index 097f976a..973fc107 100644 --- a/pkg/ethtypes/hexinteger_test.go +++ b/pkg/ethtypes/hexinteger_test.go @@ -1,4 +1,4 @@ -// Copyright © 2022 Kaleido, Inc. +// Copyright © 2024 Kaleido, Inc. // // SPDX-License-Identifier: Apache-2.0 //