forked from chappjc/dcrspy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcollector.go
345 lines (296 loc) · 9.57 KB
/
collector.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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
// Defines blockDataCollector and stakeInfoDataCollector, the client
// controllers; blockData and stakeInfoData, the data structures returned by
// the collect() methods.
//
// chappjc
package main
import (
"encoding/hex"
"errors"
"fmt"
"strconv"
"sync"
"time"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/dcrjson"
"github.com/decred/dcrd/dcrutil"
"github.com/decred/dcrd/rpcclient"
)
// WalletBalances contains various wallet balances in coins
type WalletBalances struct {
AllAllAcounts float64 `json:"allallacounts"`
AllDefaultAcount float64 `json:"alldefaultacount"`
SpendableAllAccounts float64 `json:"spendableallaccounts"`
SpendableDefaultAccount float64 `json:"spendabledefaultaccount"`
LockedAllAccounts float64 `json:"lockedallaccounts"`
LockedImportedAccount float64 `json:"lockedimportedaccount"`
LockedDefaultAccount float64 `json:"lockeddefaultaccount"`
ImmatureVotesAllAcct float64 `json:"immaturevotesallaccounts"`
ImmatureCoinbaseAllAcct float64 `json:"immaturecoinbaseallaccounts"`
}
// stakeInfoData
type stakeInfoData struct {
height uint32
walletInfo *dcrjson.WalletInfoResult
stakeinfo *dcrjson.GetStakeInfoResult
balances *WalletBalances
accountBalances *map[string]dcrjson.GetAccountBalanceResult
priceWindowNum int // trivia
idxBlockInWindow int // Relative block index within the difficulty period
}
type stakeInfoDataCollector struct {
cfg *config
dcrdChainSvr *rpcclient.Client
dcrwChainSvr *rpcclient.Client
}
// newStakeInfoDataCollector creates a new stakeInfoDataCollector.
func newStakeInfoDataCollector(cfg *config,
dcrdChainSvr *rpcclient.Client,
dcrwChainSvr *rpcclient.Client) (*stakeInfoDataCollector, error) {
return &stakeInfoDataCollector{
cfg: cfg,
dcrdChainSvr: dcrdChainSvr,
dcrwChainSvr: dcrwChainSvr,
}, nil
}
func (t stakeInfoDataCollector) getHeight() (uint32, error) {
// block height
blockCount, err := t.dcrdChainSvr.GetBlockCount()
if err != nil {
return 0, err
}
return uint32(blockCount), nil
}
// collect is the main handler for collecting chain data
func (t *stakeInfoDataCollector) collect(height uint32) (*stakeInfoData, error) {
// Time this function
defer func(start time.Time) {
log.Debugf("stakeInfoDataCollector.collect() completed in %v",
time.Since(start))
}(time.Now())
// Client pointer, simply named
wallet := t.dcrwChainSvr
// Make sure that our wallet is connected to the daemon.
var err error
var walletInfo *dcrjson.WalletInfoResult
if wallet != nil {
walletInfo, err = wallet.WalletInfo()
if err != nil {
return nil, err
}
if !walletInfo.DaemonConnected {
return nil, fmt.Errorf("Wallet not connected to daemon")
}
}
// block height
// blockCount, err := t.dcrdChainSvr.GetBlockCount()
// if err != nil {
// return nil, err
// }
// height := uint32(blockCount)
// Stake Info
getStakeInfoRes, err := wallet.GetStakeInfo()
if err != nil {
return nil, err
}
// accounts, err := wallet.ListAccounts()
// if err != nil {
// return nil, err
// }
// balTypes := []string{"total", "immature stakegen", "immature coinbase",
// "locked in tickets", "spendable", "voting authority"}
acctBals, err := wallet.GetBalanceMinConf("*", 0)
if err != nil {
return nil, err
}
var totals dcrjson.GetAccountBalanceResult
accountBalances := make(map[string]dcrjson.GetAccountBalanceResult)
for _, res := range acctBals.Balances {
accountBalances[res.AccountName] = res
totals.Total += res.Total
totals.Spendable += res.Spendable
totals.ImmatureStakeGeneration += res.ImmatureStakeGeneration
totals.ImmatureCoinbaseRewards += res.ImmatureCoinbaseRewards
totals.LockedByTickets += res.LockedByTickets
}
balAllDefault := accountBalances["default"].Total
balSpendableDefault := accountBalances["default"].Spendable
balLockedDefault := accountBalances["default"].LockedByTickets
balLockedImported := accountBalances["imported"].LockedByTickets
balances := &WalletBalances{
AllAllAcounts: totals.Total,
AllDefaultAcount: balAllDefault,
SpendableAllAccounts: totals.Spendable,
SpendableDefaultAccount: balSpendableDefault,
LockedAllAccounts: totals.LockedByTickets,
LockedImportedAccount: balLockedImported,
LockedDefaultAccount: balLockedDefault,
ImmatureVotesAllAcct: totals.ImmatureStakeGeneration,
ImmatureCoinbaseAllAcct: totals.ImmatureCoinbaseRewards,
}
// Output
winSize := uint32(activeNet.StakeDiffWindowSize)
stakeinfo := &stakeInfoData{
height: height,
walletInfo: walletInfo,
stakeinfo: getStakeInfoRes,
balances: balances,
accountBalances: &accountBalances,
priceWindowNum: int(height / winSize),
idxBlockInWindow: int(height%winSize) + 1,
}
return stakeinfo, err
}
// TicketPoolInfo models data about ticket pool
type TicketPoolInfo struct {
PoolSize uint32 `json:"poolsize"`
PoolValue float64 `json:"poolvalue"`
PoolValAvg float64 `json:"poolvalavg"`
}
// blockData
// consider if pointers are desirable here
type blockData struct {
header dcrjson.GetBlockHeaderVerboseResult
connections int32
feeinfo dcrjson.FeeInfoBlock
currentstakediff dcrjson.GetStakeDifficultyResult
eststakediff dcrjson.EstimateStakeDiffResult
poolinfo TicketPoolInfo
priceWindowNum int
idxBlockInWindow int
}
type blockDataCollector struct {
mtx sync.Mutex
cfg *config
dcrdChainSvr *rpcclient.Client
}
// newBlockDataCollector creates a new blockDataCollector.
func newBlockDataCollector(cfg *config,
dcrdChainSvr *rpcclient.Client) (*blockDataCollector, error) {
return &blockDataCollector{
mtx: sync.Mutex{},
cfg: cfg,
dcrdChainSvr: dcrdChainSvr,
}, nil
}
// collect is the main handler for collecting chain data
func (t *blockDataCollector) collect(noTicketPool bool) (*blockData, error) {
// In case of a very fast block, make sure previous call to collect is not
// still running, or dcrd may be mad.
t.mtx.Lock()
defer t.mtx.Unlock()
// Time this function
defer func(start time.Time) {
log.Debugf("blockDataCollector.collect() completed in %v", time.Since(start))
}(time.Now())
// Run first client call with a timeout
type bbhRes struct {
err error
hash *chainhash.Hash
}
toch := make(chan bbhRes)
// Pull and store relevant data about the blockchain.
go func() {
bestBlockHash, err := t.dcrdChainSvr.GetBestBlockHash()
toch <- bbhRes{err, bestBlockHash}
}()
var bbs bbhRes
select {
case bbs = <-toch:
case <-time.After(time.Second * 10):
log.Errorf("Timeout waiting for dcrd.")
return nil, errors.New("Timeout")
}
bestBlockHash := bbs.hash
bestBlock, err := t.dcrdChainSvr.GetBlock(bestBlockHash)
if err != nil {
return nil, err
}
blockHeader := bestBlock.Header
//timestamp := blockHeader.Timestamp
height := blockHeader.Height
// In datasaver.go check TicketPoolInfo.PoolValue >= 0
ticketPoolInfo := TicketPoolInfo{0, -1, -1}
if !noTicketPool {
poolSize := blockHeader.PoolSize
poolValue, err := t.dcrdChainSvr.GetTicketPoolValue()
if err != nil {
return nil, err
}
avgPricePoolAmt := dcrutil.Amount(0)
if poolSize != 0 {
avgPricePoolAmt = poolValue / dcrutil.Amount(poolSize)
}
ticketPoolInfo = TicketPoolInfo{poolSize, poolValue.ToCoin(),
avgPricePoolAmt.ToCoin()}
}
// Fee info
numFeeBlocks := uint32(1)
numFeeWindows := uint32(0)
feeInfo, err := t.dcrdChainSvr.TicketFeeInfo(&numFeeBlocks, &numFeeWindows)
if err != nil {
return nil, err
}
if len(feeInfo.FeeInfoBlocks) == 0 {
return nil, fmt.Errorf("Unable to get fee info for block %d", height)
}
feeInfoBlock := feeInfo.FeeInfoBlocks[0]
// Stake difficulty
stakeDiff, err := t.dcrdChainSvr.GetStakeDifficulty()
if err != nil {
return nil, err
}
// To get difficulty, use getinfo or getmininginfo
info, err := t.dcrdChainSvr.GetInfo()
if err != nil {
return nil, err
}
// blockVerbose, err := t.dcrdChainSvr.GetBlockVerbose(bestBlockHash, false)
// if err != nil {
// log.Error(err)
// }
// We want a GetBlockHeaderVerboseResult
// Not sure how to manage this:
//cmd := dcrjson.NewGetBlockHeaderCmd(bestBlockHash.String(), dcrjson.Bool(true))
// instead:
blockHeaderResults := dcrjson.GetBlockHeaderVerboseResult{
Hash: bestBlockHash.String(),
Confirmations: 1,
Version: blockHeader.Version,
PreviousHash: blockHeader.PrevBlock.String(),
MerkleRoot: blockHeader.MerkleRoot.String(),
StakeRoot: blockHeader.StakeRoot.String(),
VoteBits: blockHeader.VoteBits,
FinalState: hex.EncodeToString(blockHeader.FinalState[:]),
Voters: blockHeader.Voters,
FreshStake: blockHeader.FreshStake,
Revocations: blockHeader.Revocations,
PoolSize: blockHeader.PoolSize,
Bits: strconv.FormatInt(int64(blockHeader.Bits), 16),
SBits: dcrutil.Amount(blockHeader.SBits).ToCoin(),
Height: blockHeader.Height,
Size: blockHeader.Size,
Time: blockHeader.Timestamp.Unix(),
Nonce: blockHeader.Nonce,
Difficulty: info.Difficulty,
NextHash: "",
}
// estimatestakediff
estStakeDiff, err := t.dcrdChainSvr.EstimateStakeDiff(nil)
if err != nil {
return nil, err
}
// Output
winSize := uint32(activeNet.StakeDiffWindowSize)
blockdata := &blockData{
header: blockHeaderResults,
connections: info.Connections,
feeinfo: feeInfoBlock,
currentstakediff: *stakeDiff,
eststakediff: *estStakeDiff,
poolinfo: ticketPoolInfo,
priceWindowNum: int(height / winSize),
idxBlockInWindow: int(height%winSize) + 1,
}
return blockdata, err
}