Skip to content

Commit

Permalink
api: make protoFormat a bit safer to use
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mvdan authored and p4u committed Sep 3, 2024
1 parent 1a29a7f commit b5a9e14
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 6 deletions.
2 changes: 1 addition & 1 deletion api/chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
Expand Down
10 changes: 7 additions & 3 deletions api/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions api/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ func TestConvertKeysToCamel(t *testing.T) {
}
}

func TestProtoFormat(t *testing.T) {
func TestProtoTxAsJSON(t *testing.T) {
wantJSON := strings.TrimSpace(`
{
"setProcess": {
Expand All @@ -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()

Expand Down

0 comments on commit b5a9e14

Please sign in to comment.