-
Notifications
You must be signed in to change notification settings - Fork 4
/
monerorpc.go
82 lines (71 loc) · 2.02 KB
/
monerorpc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package monerorpc
import (
"bytes"
"fmt"
"net/http"
"github.com/MarinX/monerorpc/daemon"
"github.com/MarinX/monerorpc/wallet"
"github.com/gabstv/httpdigest"
"github.com/gorilla/rpc/v2/json2"
)
const (
// TestnetURI local testnet monerod instance
TestnetURI = "http://127.0.0.1:28081/json_rpc"
// StagnetURI local stagnet monerod instance
StagnetURI = "http://127.0.0.1:38080/json_rpc"
// ProdnetURI local production monerod instance
ProdnetURI = "http://127.0.0.1:18080/json_rpc"
)
// MoneroRPC holds json rpc http client for various monero calls
type MoneroRPC struct {
client *http.Client
uri string
Wallet wallet.Wallet
Daemon daemon.Daemon
}
// New creates a new MoneroRPC client
func New(endpoint string, httpClient *http.Client) *MoneroRPC {
cli := http.DefaultClient
if httpClient != nil {
cli = httpClient
}
client := &MoneroRPC{
client: cli,
uri: endpoint,
}
client.Wallet = wallet.New(client)
client.Daemon = daemon.New(client)
return client
}
// SetAuth sets digest username and password to be used with client
func (c *MoneroRPC) SetAuth(username, password string) *MoneroRPC {
c.client.Transport = httpdigest.New(username, password)
return c
}
// Do calls monero json rpc server, usefull if you are calling undocumented API
func (c *MoneroRPC) Do(method string, req interface{}, res interface{}) error {
buff, err := json2.EncodeClientRequest(method, req)
if err != nil {
return fmt.Errorf("error creating encoded request %v", err)
}
httpReq, err := http.NewRequest("POST", c.uri, bytes.NewReader(buff))
if err != nil {
return fmt.Errorf("error creating http request %v", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpResp, err := c.client.Do(httpReq)
if err != nil {
return err
}
defer httpResp.Body.Close()
if httpResp.StatusCode == http.StatusUnauthorized {
return fmt.Errorf("unauthorized - invalid username or password")
}
if res != nil {
err = json2.DecodeClientResponse(httpResp.Body, res)
if err == json2.ErrNullResult {
return nil
}
}
return err
}