diff --git a/rpc/types.go b/rpc/types.go index e7f0107ce5..04d1214e16 100644 --- a/rpc/types.go +++ b/rpc/types.go @@ -235,6 +235,16 @@ func (bnh *BlockNumberOrHash) Number() (BlockNumber, bool) { return BlockNumber(0), false } +func (bnh *BlockNumberOrHash) String() string { + if bnh.BlockNumber != nil { + return bnh.BlockNumber.String() + } + if bnh.BlockHash != nil { + return bnh.BlockHash.String() + } + return "nil" +} + func (bnh *BlockNumberOrHash) Hash() (common.Hash, bool) { if bnh.BlockHash != nil { return *bnh.BlockHash, true diff --git a/rpc/types_test.go b/rpc/types_test.go index f2019c43e7..861fe01165 100644 --- a/rpc/types_test.go +++ b/rpc/types_test.go @@ -155,3 +155,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) + } + } +}