From 271264e33c4c351de21ed8de031dc68953d0d3fe Mon Sep 17 00:00:00 2001 From: Joshua Sing Date: Thu, 23 May 2024 01:28:40 +1000 Subject: [PATCH] electrumx: fix unhandled error in NewJSONRPCRequest --- hemi/electrumx/conn.go | 7 +++++-- hemi/electrumx/conn_test.go | 12 ++++++++++-- hemi/electrumx/electrumx.go | 5 +++-- 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/hemi/electrumx/conn.go b/hemi/electrumx/conn.go index 532d2795..b40923c8 100644 --- a/hemi/electrumx/conn.go +++ b/hemi/electrumx/conn.go @@ -53,8 +53,11 @@ func (c *clientConn) call(ctx context.Context, method string, params, result any defer c.mx.Unlock() c.requestID++ - req := NewJSONRPCRequest(c.requestID, method, params) - if err := writeRequest(ctx, c.conn, req); err != nil { + req, err := NewJSONRPCRequest(c.requestID, method, params) + if err != nil { + return fmt.Errorf("create request: %w", err) + } + if err = writeRequest(ctx, c.conn, req); err != nil { return fmt.Errorf("write request: %w", err) } diff --git a/hemi/electrumx/conn_test.go b/hemi/electrumx/conn_test.go index 9a2fd72e..09216ef9 100644 --- a/hemi/electrumx/conn_test.go +++ b/hemi/electrumx/conn_test.go @@ -80,12 +80,12 @@ func TestWriteRequest(t *testing.T) { }{ { name: "simple", - req: NewJSONRPCRequest(1, "test", nil), + req: mustNewJSONRPCRequest(1, "test", nil), want: "{\"jsonrpc\":\"2.0\",\"method\":\"test\",\"id\":1}\n", }, { name: "with params", - req: NewJSONRPCRequest(2, "test", map[string]any{ + req: mustNewJSONRPCRequest(2, "test", map[string]any{ "test": true, }), want: "{\"jsonrpc\":\"2.0\",\"method\":\"test\",\"params\":{\"test\":true},\"id\":2}\n", @@ -303,3 +303,11 @@ func createAddress() string { } return fmt.Sprintf("localhost:%d", port) } + +func mustNewJSONRPCRequest(id uint64, method string, params any) *JSONRPCRequest { + req, err := NewJSONRPCRequest(id, method, params) + if err != nil { + panic(fmt.Errorf("create JSON RPC request: %w", err)) + } + return req +} diff --git a/hemi/electrumx/electrumx.go b/hemi/electrumx/electrumx.go index 55a72464..2b11e3ed 100644 --- a/hemi/electrumx/electrumx.go +++ b/hemi/electrumx/electrumx.go @@ -36,7 +36,7 @@ type JSONRPCRequest struct { } // NewJSONRPCRequest creates a new JSONRPCRequest. -func NewJSONRPCRequest(id uint64, method string, params any) *JSONRPCRequest { +func NewJSONRPCRequest(id uint64, method string, params any) (*JSONRPCRequest, error) { req := &JSONRPCRequest{ JSONRPC: "2.0", Method: method, @@ -45,10 +45,11 @@ func NewJSONRPCRequest(id uint64, method string, params any) *JSONRPCRequest { if params != nil { b, err := json.Marshal(params) if err != nil { + return nil, fmt.Errorf("marshal params: %w", err) } req.Params = b } - return req + return req, nil } type JSONRPCResponse struct {