From b5a9e140f7bf83c027908adeb71c34d287b9323a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Mart=C3=AD?= Date: Wed, 28 Aug 2024 23:45:47 +0100 Subject: [PATCH] api: make protoFormat a bit safer to use Give it a better name, as it has little to do with formatting. Make it return bytes, which is what we need. Don't let it silently ignore errors, which could cause issues. Use the Marshal protobuf func, as Format is only for debugging. --- api/chain.go | 2 +- api/helpers.go | 10 +++++++--- api/helpers_test.go | 4 ++-- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/api/chain.go b/api/chain.go index 7907d5d99..8c081bd89 100644 --- a/api/chain.go +++ b/api/chain.go @@ -706,7 +706,7 @@ func (a *API) chainTxHandler(_ *apirest.APIdata, ctx *httprouter.HTTPContext) er return ErrVochainGetTxFailed.WithErr(err) } tx := &GenericTransactionWithInfo{ - TxContent: []byte(protoFormat(stx.Tx)), + TxContent: protoTxAsJSON(stx.Tx), Signature: stx.Signature, TxInfo: *ref, } diff --git a/api/helpers.go b/api/helpers.go index 3c47b4ac2..a7431c296 100644 --- a/api/helpers.go +++ b/api/helpers.go @@ -57,17 +57,21 @@ func (a *API) sendTx(tx []byte) (*cometcoretypes.ResultBroadcastTx, error) { return resp, nil } -func protoFormat(tx []byte) string { +func protoTxAsJSON(tx []byte) []byte { ptx := models.Tx{} if err := proto.Unmarshal(tx, &ptx); err != nil { - return "" + panic(err) } pj := protojson.MarshalOptions{ Multiline: false, Indent: "", EmitUnpopulated: true, } - return pj.Format(&ptx) + asJSON, err := pj.Marshal(&ptx) + if err != nil { + panic(err) + } + return asJSON } // isTransactionType checks if the given transaction is of the given type. diff --git a/api/helpers_test.go b/api/helpers_test.go index 21eb82820..489a64e9b 100644 --- a/api/helpers_test.go +++ b/api/helpers_test.go @@ -155,7 +155,7 @@ func TestConvertKeysToCamel(t *testing.T) { } } -func TestProtoFormat(t *testing.T) { +func TestProtoTxAsJSON(t *testing.T) { wantJSON := strings.TrimSpace(` { "setProcess": { @@ -176,7 +176,7 @@ func TestProtoFormat(t *testing.T) { qt.Assert(t, err, qt.IsNil) var dst bytes.Buffer - err = json.Indent(&dst, []byte(protoFormat(asProto)), "", "\t") + err = json.Indent(&dst, protoTxAsJSON(asProto), "", "\t") qt.Assert(t, err, qt.IsNil) gotJSON := dst.String()