Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions core/rpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"io"
"log"
"net/http"
"net/url"
"sync"
"sync/atomic"
"time"
Expand All @@ -32,13 +33,22 @@ const (

// NewCoreRPCClient returns a Dogecoin Core Node client.
// Thread-safe, can be shared across Goroutines.
func NewCoreRPCClient(rpcHost string, rpcPort int, rpcUser string, rpcPass string) spec.Blockchain {
url := fmt.Sprintf("http://%s:%d", rpcHost, rpcPort)
return &CoreRPCClient{url: url, user: rpcUser, pass: rpcPass, retryDelay: 5 * time.Second}
// If rpcHostOrUrl is a URL, it will be used directly.
// If rpcHostOrUrl is a hostname, it will be used with the port.
func NewCoreRPCClient(rpcHostOrUrl string, rpcPort int, rpcUser string, rpcPass string) spec.Blockchain {
parsedUrl, err := url.Parse(rpcHostOrUrl)
var url string
if err != nil || parsedUrl.Scheme == "" {
url = fmt.Sprintf("http://%s:%d", rpcHostOrUrl, rpcPort)
} else {
url = rpcHostOrUrl
}

return &CoreRPCClient{URL: url, user: rpcUser, pass: rpcPass, retryDelay: 5 * time.Second}
}

type CoreRPCClient struct {
url string
URL string
user string
pass string
id atomic.Uint64 // next unique request id
Expand Down Expand Up @@ -364,7 +374,7 @@ func (c *CoreRPCClient) Request(ctx context.Context, method string, params []any
if err != nil {
return 0, fmt.Errorf("json-rpc marshal request: %v", err)
}
req, err := http.NewRequestWithContext(ctx, "POST", c.url, bytes.NewBuffer(payload))
req, err := http.NewRequestWithContext(ctx, "POST", c.URL, bytes.NewBuffer(payload))
if err != nil {
return 0, fmt.Errorf("json-rpc request: %v", err)
}
Expand Down
27 changes: 27 additions & 0 deletions core/rpc_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package core

import (
"testing"
)

func TestNewCoreRPCClient(t *testing.T) {
rpc := NewCoreRPCClient("http://127.0.0.1:22555", 0, "dogecoin", "dogecoin")
if rpc == nil {
t.Fatal("NewCoreRPCClient returned nil")
}

if rpc.(*CoreRPCClient).URL != "http://127.0.0.1:22555" {
t.Fatal("GetURL returned wrong URL")
}
}

func TestNewCoreRPCClientWithHostname(t *testing.T) {
rpc := NewCoreRPCClient("hostname", 22555, "dogecoin", "dogecoin")
if rpc == nil {
t.Fatal("NewCoreRPCClient returned nil")
}

if rpc.(*CoreRPCClient).URL != "http://hostname:22555" {
t.Fatal("GetURL returned wrong URL")
}
}