rpc: use correct stringer-method for serializing BlockNumberOrHash (#28358)

Switch to using BlockNumber.String() which encodes it correctly for use in the JSON-RPC API.
This commit is contained in:
Adrian Sutton 2023-10-25 23:52:42 +10:00 committed by zzzckck
parent f4b7cdfe38
commit ca058b7a69
3 changed files with 23 additions and 3 deletions

@ -21,7 +21,6 @@ import (
"encoding/json"
"fmt"
"math"
"strconv"
"strings"
"github.com/ethereum/go-ethereum/common"
@ -221,7 +220,7 @@ func (bnh *BlockNumberOrHash) Number() (BlockNumber, bool) {
func (bnh *BlockNumberOrHash) String() string {
if bnh.BlockNumber != nil {
return strconv.Itoa(int(*bnh.BlockNumber))
return bnh.BlockNumber.String()
}
if bnh.BlockHash != nil {
return bnh.BlockHash.String()

@ -153,3 +153,24 @@ func TestBlockNumberOrHash_WithNumber_MarshalAndUnmarshal(t *testing.T) {
})
}
}
func TestBlockNumberOrHash_StringAndUnmarshal(t *testing.T) {
tests := []BlockNumberOrHash{
BlockNumberOrHashWithNumber(math.MaxInt64),
BlockNumberOrHashWithNumber(PendingBlockNumber),
BlockNumberOrHashWithNumber(LatestBlockNumber),
BlockNumberOrHashWithNumber(EarliestBlockNumber),
BlockNumberOrHashWithNumber(32),
BlockNumberOrHashWithHash(common.Hash{0xaa}, false),
}
for _, want := range tests {
marshalled, _ := json.Marshal(want.String())
var have BlockNumberOrHash
if err := json.Unmarshal(marshalled, &have); err != nil {
t.Fatalf("cannot unmarshal (%v): %v", string(marshalled), err)
}
if !reflect.DeepEqual(want, have) {
t.Fatalf("wrong result: have %v, want %v", have, want)
}
}
}