From 7f15befdeeb5b0f946308d26b39b25aefebededb Mon Sep 17 00:00:00 2001 From: prathamesh0 Date: Mon, 30 May 2022 18:09:50 +0530 Subject: [PATCH] Add custom implementation for Bytes to be returned as string --- pkg/graphql/graphql.go | 6 +++--- pkg/graphql/types.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/pkg/graphql/graphql.go b/pkg/graphql/graphql.go index 19480ab5..1c8cc31b 100644 --- a/pkg/graphql/graphql.go +++ b/pkg/graphql/graphql.go @@ -1327,7 +1327,7 @@ func (r *Resolver) AllEthHeaderCids(ctx context.Context, args struct { txRoot: headerCID.TxRoot, receiptRoot: headerCID.RctRoot, uncleRoot: headerCID.UncleRoot, - bloom: hexutil.Bytes(headerCID.Bloom).String(), + bloom: Bytes(headerCID.Bloom).String(), } txCIDs := allTxCIDs[idx] @@ -1343,7 +1343,7 @@ func (r *Resolver) AllEthHeaderCids(ctx context.Context, args struct { ethHeaderCidNode.ipfsBlock = IPFSBlock{ key: headerIPLDs[idx].Key, - data: hexutil.Bytes(headerIPLDs[idx].Data).String(), + data: Bytes(headerIPLDs[idx].Data).String(), } resultNodes = append(resultNodes, ðHeaderCidNode) @@ -1392,7 +1392,7 @@ func (r *Resolver) EthTransactionCidByTxHash(ctx context.Context, args struct { dst: txCID.Dst, ipfsBlock: IPFSBlock{ key: txIPLDs[0].Key, - data: hexutil.Bytes(txIPLDs[0].Data).String(), + data: Bytes(txIPLDs[0].Data).String(), }, }, nil } diff --git a/pkg/graphql/types.go b/pkg/graphql/types.go index 2756070d..7213cecc 100644 --- a/pkg/graphql/types.go +++ b/pkg/graphql/types.go @@ -17,12 +17,40 @@ package graphql import ( + "encoding/hex" "fmt" "math/big" "github.com/ethereum/go-ethereum/common/hexutil" ) +// Bytes marshals as a JSON string with \x prefix. +// The empty slice marshals as "\x". +type Bytes []byte + +// MarshalText implements encoding.TextMarshaler +func (b Bytes) MarshalText() ([]byte, error) { + result := make([]byte, len(b)*2+2) + copy(result, `\x`) + hex.Encode(result[2:], b) + return result, nil +} + +// String returns the hex encoding of b. +func (b Bytes) String() string { + return b.encode() +} + +// Encode encodes b as a hex string with "\x" prefix. +// This is to make the output to be the same as given by postgraphile. +// graphql-go prepends another "\" to the output resulting in prefix "\\x". +func (b Bytes) encode() string { + result := make([]byte, len(b)*2+2) + copy(result, `\x`) + hex.Encode(result[2:], b) + return string(result) +} + type BigInt big.Int // ToInt converts b to a big.Int.