/
rpcclient.go
222 lines (193 loc) · 6.82 KB
/
rpcclient.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
// Copyright (c) 2017, Jonathan Chappelow
// See LICENSE for details.
package rpcutils
import (
"encoding/hex"
"fmt"
"io/ioutil"
"strconv"
apitypes "github.com/dcrdata/dcrdata/dcrdataapi"
"github.com/dcrdata/dcrdata/semver"
"github.com/dcrdata/dcrdata/txhelpers"
"github.com/decred/dcrd/chaincfg"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/dcrjson"
"github.com/decred/dcrd/wire"
"github.com/decred/dcrrpcclient"
"github.com/decred/dcrutil"
)
var requiredChainServerAPI = semver.NewSemver(3, 0, 0)
// ConnectNodeRPC attempts to create a new websocket connection to a dcrd node,
// with the given credentials and optional notification handlers.
func ConnectNodeRPC(host, user, pass, cert string, disableTLS bool,
ntfnHandlers ...*dcrrpcclient.NotificationHandlers) (*dcrrpcclient.Client, semver.Semver, error) {
var dcrdCerts []byte
var err error
var nodeVer semver.Semver
if !disableTLS {
dcrdCerts, err = ioutil.ReadFile(cert)
if err != nil {
log.Errorf("Failed to read dcrd cert file at %s: %s\n",
cert, err.Error())
return nil, nodeVer, err
}
log.Debugf("Attempting to connect to dcrd RPC %s as user %s "+
"using certificate located in %s",
host, user, cert)
} else {
log.Debugf("Attempting to connect to dcrd RPC %s as user %s (no TLS)",
host, user)
}
connCfgDaemon := &dcrrpcclient.ConnConfig{
Host: host,
Endpoint: "ws", // websocket
User: user,
Pass: pass,
Certificates: dcrdCerts,
DisableTLS: disableTLS,
}
var ntfnHdlrs *dcrrpcclient.NotificationHandlers
if len(ntfnHandlers) > 0 {
if len(ntfnHandlers) > 1 {
return nil, nodeVer, fmt.Errorf("Invalid notification handler argument")
}
ntfnHdlrs = ntfnHandlers[0]
}
dcrdClient, err := dcrrpcclient.New(connCfgDaemon, ntfnHdlrs)
if err != nil {
return nil, nodeVer, fmt.Errorf("Failed to start dcrd RPC client: %s", err.Error())
}
// Ensure the RPC server has a compatible API version.
ver, err := dcrdClient.Version()
if err != nil {
log.Error("Unable to get RPC version: ", err)
return nil, nodeVer, fmt.Errorf("Unable to get node RPC version")
}
dcrdVer := ver["dcrdjsonrpcapi"]
nodeVer = semver.NewSemver(dcrdVer.Major, dcrdVer.Minor, dcrdVer.Patch)
if !semver.SemverCompatible(requiredChainServerAPI, nodeVer) {
return nil, nodeVer, fmt.Errorf("Node JSON-RPC server does not have "+
"a compatible API version. Advertises %v but require %v",
nodeVer, requiredChainServerAPI)
}
return dcrdClient, nodeVer, nil
}
// BuildBlockHeaderVerbose creates a *dcrjson.GetBlockHeaderVerboseResult from
// an input *wire.BlockHeader and current best block height, which is used to
// compute confirmations. The next block hash may optionally be provided.
func BuildBlockHeaderVerbose(header *wire.BlockHeader, params *chaincfg.Params,
currentHeight int64, nextHash ...string) *dcrjson.GetBlockHeaderVerboseResult {
if header == nil {
return nil
}
diffRatio := txhelpers.GetDifficultyRatio(header.Bits, params)
var next string
if len(nextHash) > 0 {
next = nextHash[0]
}
blockHeaderResult := dcrjson.GetBlockHeaderVerboseResult{
Hash: header.BlockHash().String(),
Confirmations: int64(currentHeight - int64(header.Height)),
Version: header.Version,
PreviousHash: header.PrevBlock.String(),
MerkleRoot: header.MerkleRoot.String(),
StakeRoot: header.StakeRoot.String(),
VoteBits: header.VoteBits,
FinalState: hex.EncodeToString(header.FinalState[:]),
Voters: header.Voters,
FreshStake: header.FreshStake,
Revocations: header.Revocations,
PoolSize: header.PoolSize,
Bits: strconv.FormatInt(int64(header.Bits), 16),
SBits: dcrutil.Amount(header.SBits).ToCoin(),
Height: header.Height,
Size: header.Size,
Time: header.Timestamp.Unix(),
Nonce: header.Nonce,
Difficulty: diffRatio,
NextHash: next,
}
return &blockHeaderResult
}
// GetBlockHeaderVerbose creates a *dcrjson.GetBlockHeaderVerboseResult for the
// block index specified by idx via an RPC connection to a chain server.
func GetBlockHeaderVerbose(client *dcrrpcclient.Client, params *chaincfg.Params,
idx int64) *dcrjson.GetBlockHeaderVerboseResult {
blockhash, err := client.GetBlockHash(idx)
if err != nil {
log.Errorf("GetBlockHash(%d) failed: %v", idx, err)
return nil
}
blockHeaderVerbose, err := client.GetBlockHeaderVerbose(blockhash)
if err != nil {
log.Errorf("GetBlockHeaderVerbose(%v) failed: %v", blockhash, err)
return nil
}
return blockHeaderVerbose
}
// GetBlockVerbose creates a *dcrjson.GetBlockVerboseResult for the block index
// specified by idx via an RPC connection to a chain server.
func GetBlockVerbose(client *dcrrpcclient.Client, params *chaincfg.Params,
idx int64, verboseTx bool) *dcrjson.GetBlockVerboseResult {
blockhash, err := client.GetBlockHash(idx)
if err != nil {
log.Errorf("GetBlockHash(%d) failed: %v", idx, err)
return nil
}
blockVerbose, err := client.GetBlockVerbose(blockhash, verboseTx)
if err != nil {
log.Errorf("GetBlockVerbose(%v) failed: %v", blockhash, err)
return nil
}
return blockVerbose
}
// GetBlockVerboseByHash creates a *dcrjson.GetBlockVerboseResult for the
// specified block hash via an RPC connection to a chain server.
func GetBlockVerboseByHash(client *dcrrpcclient.Client, params *chaincfg.Params,
hash string, verboseTx bool) *dcrjson.GetBlockVerboseResult {
blockhash, err := chainhash.NewHashFromStr(hash)
if err != nil {
log.Errorf("Invalid block hash %s", hash)
return nil
}
blockVerbose, err := client.GetBlockVerbose(blockhash, verboseTx)
if err != nil {
log.Errorf("GetBlockVerbose(%v) failed: %v", blockhash, err)
return nil
}
return blockVerbose
}
// GetStakeDiffEstimates combines the results of EstimateStakeDiff and
// GetStakeDifficulty into a *apitypes.StakeDiff.
func GetStakeDiffEstimates(client *dcrrpcclient.Client) *apitypes.StakeDiff {
stakeDiff, err := client.GetStakeDifficulty()
if err != nil {
return nil
}
estStakeDiff, err := client.EstimateStakeDiff(nil)
if err != nil {
return nil
}
stakeDiffEstimates := apitypes.StakeDiff{
GetStakeDifficultyResult: dcrjson.GetStakeDifficultyResult{
CurrentStakeDifficulty: stakeDiff.CurrentStakeDifficulty,
NextStakeDifficulty: stakeDiff.NextStakeDifficulty,
},
Estimates: *estStakeDiff,
}
return &stakeDiffEstimates
}
// GetBlock gets a block at the given height from a chain server.
func GetBlock(ind int64, client *dcrrpcclient.Client) (*dcrutil.Block, *chainhash.Hash, error) {
blockhash, err := client.GetBlockHash(ind)
if err != nil {
return nil, nil, fmt.Errorf("GetBlockHash(%d) failed: %v", ind, err)
}
msgBlock, err := client.GetBlock(blockhash)
if err != nil {
return nil, blockhash,
fmt.Errorf("GetBlock failed (%s): %v", blockhash, err)
}
block := dcrutil.NewBlock(msgBlock)
return block, blockhash, nil
}