Skip to content
This repository was archived by the owner on Dec 23, 2024. It is now read-only.

Commit d8c6ae0

Browse files
authored
rpc: use correct stringer-method for serializing BlockNumberOrHash (#28358)
The String() version of BlockNumberOrHash uses decimal for all block numbers, including negative ones used to indicate labels. Switch to using BlockNumber.String() which encodes it correctly for use in the JSON-RPC API.
1 parent f7b62e5 commit d8c6ae0

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

rpc/types.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ import (
2121
"encoding/json"
2222
"fmt"
2323
"math"
24-
"strconv"
2524
"strings"
2625

2726
"github.com/ethereum/go-ethereum/common"
@@ -221,7 +220,7 @@ func (bnh *BlockNumberOrHash) Number() (BlockNumber, bool) {
221220

222221
func (bnh *BlockNumberOrHash) String() string {
223222
if bnh.BlockNumber != nil {
224-
return strconv.Itoa(int(*bnh.BlockNumber))
223+
return bnh.BlockNumber.String()
225224
}
226225
if bnh.BlockHash != nil {
227226
return bnh.BlockHash.String()

rpc/types_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,3 +153,24 @@ func TestBlockNumberOrHash_WithNumber_MarshalAndUnmarshal(t *testing.T) {
153153
})
154154
}
155155
}
156+
157+
func TestBlockNumberOrHash_StringAndUnmarshal(t *testing.T) {
158+
tests := []BlockNumberOrHash{
159+
BlockNumberOrHashWithNumber(math.MaxInt64),
160+
BlockNumberOrHashWithNumber(PendingBlockNumber),
161+
BlockNumberOrHashWithNumber(LatestBlockNumber),
162+
BlockNumberOrHashWithNumber(EarliestBlockNumber),
163+
BlockNumberOrHashWithNumber(32),
164+
BlockNumberOrHashWithHash(common.Hash{0xaa}, false),
165+
}
166+
for _, want := range tests {
167+
marshalled, _ := json.Marshal(want.String())
168+
var have BlockNumberOrHash
169+
if err := json.Unmarshal(marshalled, &have); err != nil {
170+
t.Fatalf("cannot unmarshal (%v): %v", string(marshalled), err)
171+
}
172+
if !reflect.DeepEqual(want, have) {
173+
t.Fatalf("wrong result: have %v, want %v", have, want)
174+
}
175+
}
176+
}

0 commit comments

Comments
 (0)