-
Notifications
You must be signed in to change notification settings - Fork 50
/
service.go
431 lines (377 loc) · 10.5 KB
/
service.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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
// Copyright (c) 2017-2024 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"sync"
"time"
"github.com/decred/dcrd/dcrutil/v4"
apitypes "github.com/decred/dcrdata/v6/api/types"
"github.com/decred/dcrdata/v6/db/dbtypes"
)
// Vsp contains information about a single Voting Service Provider. Includes
// info hard-coded in dcrwebapi and info retrieved from the VSPs /vspinfo
// endpoint.
type Vsp struct {
// Hard-coded in dcrwebapi.
Network string `json:"network"`
Launched int64 `json:"launched"`
// Set by dcrwebapi each time info is successfully updated.
LastUpdated int64 `json:"lastupdated"`
// Retrieved from the /api/vspinfo.
APIVersions []int64 `json:"apiversions"`
FeePercentage float64 `json:"feepercentage"`
Closed bool `json:"closed"`
Voting int64 `json:"voting"`
Voted int64 `json:"voted"`
Revoked int64 `json:"revoked"`
Expired int64 `json:"expired"`
Missed int64 `json:"missed"`
VspdVersion string `json:"vspdversion"`
BlockHeight uint64 `json:"blockheight"`
EstimatedNetworkProportion float64 `json:"estimatednetworkproportion"`
}
type vspSet map[string]Vsp
type priceInfo struct {
BitcoinUSD float64 `json:"bitcoin_usd"`
DecredUSD float64 `json:"decred_usd"`
LastUpdated int64 `json:"lastupdated"`
}
type webInfo struct {
Circulating float64 `json:"circulatingsupply"`
Ultimate float64 `json:"ultimatesupply"`
Staked float64 `json:"stakedsupply"`
BlockReward float64 `json:"blockreward"`
Treasury float64 `json:"treasury"`
TicketPrice float64 `json:"ticketprice"`
Height uint32 `json:"height"`
LastUpdated int64 `json:"lastupdated"`
}
// Service represents a dcrweb service.
type Service struct {
// the http client
HTTPClient *http.Client
// the http router
Router *http.ServeMux
// Data cached by the service, protected by a mutex.
Vsps vspSet
WebInfo webInfo
PriceInfo priceInfo
Mutex sync.RWMutex
}
// NewService creates a new dcrwebapi service.
func NewService() *Service {
service := Service{
HTTPClient: &http.Client{
Transport: &http.Transport{
MaxIdleConnsPerHost: 2,
},
Timeout: time.Second * 10,
},
Router: http.NewServeMux(),
Mutex: sync.RWMutex{},
Vsps: vspSet{
"teststakepool.decred.org": Vsp{
Network: "testnet",
Launched: getUnixTime(2020, 6, 1),
},
"testnet-vsp.jholdstock.uk": Vsp{
Network: "testnet",
Launched: getUnixTime(2021, 1, 20),
},
"dcrvsp.ubiqsmart.com": Vsp{
Network: "mainnet",
Launched: getUnixTime(2020, 12, 25),
},
"stakey.net": Vsp{
Network: "mainnet",
Launched: getUnixTime(2020, 10, 22),
},
"vsp.stakeminer.com": Vsp{
Network: "mainnet",
Launched: getUnixTime(2020, 11, 9),
},
"vsp.decredcommunity.org": Vsp{
Network: "mainnet",
Launched: getUnixTime(2020, 11, 05),
},
"vspd.99split.com": Vsp{
Network: "mainnet",
Launched: getUnixTime(2020, 11, 17),
},
"vspd.decredbrasil.com": Vsp{
Network: "mainnet",
Launched: getUnixTime(2020, 11, 22),
},
"ultravsp.uk": Vsp{
Network: "mainnet",
Launched: getUnixTime(2020, 12, 1),
},
"vsp.dcr.farm": Vsp{
Network: "mainnet",
Launched: getUnixTime(2020, 12, 9),
},
"decredvoting.com": Vsp{
Network: "mainnet",
Launched: getUnixTime(2021, 2, 1),
},
"decred.stake.fun": Vsp{
Network: "mainnet",
Launched: getUnixTime(2021, 1, 28),
},
"big.decred.energy": {
Network: "mainnet",
Launched: getUnixTime(2022, 5, 1),
},
"dcrhive.com": {
Network: "mainnet",
Launched: getUnixTime(2022, 6, 23),
},
"vspd.bass.cf": {
Network: "mainnet",
Launched: getUnixTime(2022, 5, 1),
},
"vote.dcr-swiss.ch": {
Network: "mainnet",
Launched: getUnixTime(2023, 6, 30),
},
},
}
// Start update ticker.
go func() {
for {
vspData(&service)
err := info(&service)
if err != nil {
log.Printf("Error updating web info: %v", err)
}
err = price(&service)
if err != nil {
log.Printf("Error updating price info: %v", err)
}
<-time.After(time.Minute * 5)
}
}()
// setup route
service.Router.HandleFunc("/", service.HandleRoutes)
return &service
}
// getHTTP will use the services HTTP client to send a GET request to the
// provided URL. Returns the response body, or an error.
func (service *Service) getHTTP(url string) ([]byte, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, fmt.Errorf("%v: failed to create request: %v",
url, err)
}
req.Header.Set("User-Agent", "decred/dcrweb bot")
poolResp, err := service.HTTPClient.Do(req)
if err != nil {
return nil, fmt.Errorf("%v: failed to send request: %v",
url, err)
}
defer poolResp.Body.Close()
if poolResp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%v: non-success status: %d",
url, poolResp.StatusCode)
}
respBody, err := io.ReadAll(poolResp.Body)
if err != nil {
return nil, fmt.Errorf("%v: failed to read body: %v",
url, err)
}
return respBody, nil
}
func vspStats(service *Service, url string) error {
var vsp Vsp
service.Mutex.RLock()
vsp = service.Vsps[url]
service.Mutex.RUnlock()
infoURL := fmt.Sprintf("https://%s/api/v3/vspinfo", url)
infoResp, err := service.getHTTP(infoURL)
if err != nil {
return err
}
var info map[string]interface{}
err = json.Unmarshal(infoResp, &info)
if err != nil {
return fmt.Errorf("%v: unmarshal failed: %v",
infoURL, err)
}
apiversions, hasAPIVersions := info["apiversions"]
feepercentage, hasFeePercentage := info["feepercentage"]
vspclosed, hasClosed := info["vspclosed"]
voting, hasVoting := info["voting"]
voted, hasVoted := info["voted"]
revoked, hasRevoked := info["revoked"]
expired, hasExpired := info["expired"]
missed, hasMissed := info["missed"]
version, hasVersion := info["vspdversion"]
blockheight, hasBlockHeight := info["blockheight"]
networkproportion, hasnetworkproportion := info["estimatednetworkproportion"]
hasRequiredFields := hasAPIVersions && hasFeePercentage &&
hasClosed && hasVoting && hasVoted && hasRevoked && hasVersion &&
hasBlockHeight && hasnetworkproportion
if !hasRequiredFields {
return fmt.Errorf("%v: missing required fields: %+v", infoURL, info)
}
vsp.APIVersions = make([]int64, 0)
for _, i := range apiversions.([]interface{}) {
vsp.APIVersions = append(vsp.APIVersions, int64(i.(float64)))
}
vsp.FeePercentage = feepercentage.(float64)
vsp.Closed = vspclosed.(bool)
vsp.Voting = int64(voting.(float64))
vsp.Voted = int64(voted.(float64))
vsp.Revoked = int64(revoked.(float64))
vsp.VspdVersion = version.(string)
vsp.BlockHeight = uint64(blockheight.(float64))
vsp.EstimatedNetworkProportion = networkproportion.(float64)
// Expired and Missed were introduced in vspd 1.3.0 so they will be absent
// from the responses received from older versions. When every VSP is
// updated to 1.3.0+ these fields can be treated like every other required
// field.
if hasExpired {
vsp.Expired = int64(expired.(float64))
}
if hasMissed {
vsp.Missed = int64(missed.(float64))
}
vsp.LastUpdated = time.Now().Unix()
service.Mutex.Lock()
service.Vsps[url] = vsp
service.Mutex.Unlock()
return nil
}
func vspData(service *Service) {
var waitGroup sync.WaitGroup
waitGroup.Add(len(service.Vsps))
for url := range service.Vsps {
go func(url string) {
defer waitGroup.Done()
err := vspStats(service, url)
if err != nil {
log.Println(err)
}
}(url)
}
waitGroup.Wait()
}
// dcrdata gets an API response from dcrdata and unmarshals it.
func (service *Service) dcrdata(path string, response interface{}) error {
body, err := service.getHTTP("https://dcrdata.decred.org/api" + path)
if err != nil {
return err
}
err = json.Unmarshal(body, response)
if err != nil {
return err
}
return nil
}
func price(service *Service) error {
var exchange struct {
DcrPrice float64 `json:"dcrPrice"`
BtcPrice float64 `json:"btcPrice"`
}
err := service.dcrdata("/exchangerate", &exchange)
if err != nil {
return err
}
service.Mutex.Lock()
service.PriceInfo = priceInfo{
BitcoinUSD: exchange.BtcPrice,
DecredUSD: exchange.DcrPrice,
LastUpdated: time.Now().Unix(),
}
service.Mutex.Unlock()
return nil
}
func info(service *Service) error {
var supply apitypes.CoinSupply
err := service.dcrdata("/supply", &supply)
if err != nil {
return err
}
var bestBlock apitypes.BlockDataBasic
err = service.dcrdata("/block/best", &bestBlock)
if err != nil {
return err
}
var treasury dbtypes.TreasuryBalance
err = service.dcrdata("/treasury/balance", &treasury)
if err != nil {
return err
}
var subsidy apitypes.BlockSubsidies
err = service.dcrdata("/block/best/subsidy", &subsidy)
if err != nil {
return err
}
// toDCR converts atoms to DCR.
toDCR := func(atoms int64) float64 {
return dcrutil.Amount(atoms).ToCoin()
}
service.Mutex.Lock()
service.WebInfo = webInfo{
Circulating: toDCR(supply.Mined),
Ultimate: toDCR(supply.Ultimate),
Staked: bestBlock.PoolInfo.Value,
BlockReward: toDCR(subsidy.Work * 100),
Treasury: toDCR(treasury.Balance),
TicketPrice: bestBlock.StakeDiff,
Height: bestBlock.Height,
LastUpdated: time.Now().Unix(),
}
service.Mutex.Unlock()
return nil
}
// HandleRoutes is the handler func for all endpoints exposed by the service
func (service *Service) HandleRoutes(writer http.ResponseWriter, request *http.Request) {
err := request.ParseForm()
if err != nil {
writeJSONErrorResponse(&writer, err)
return
}
route := request.FormValue("c")
switch route {
case "vsp":
service.Mutex.RLock()
respJSON, err := json.Marshal(service.Vsps)
service.Mutex.RUnlock()
if err != nil {
writeJSONErrorResponse(&writer, err)
return
}
writeJSONResponse(&writer, http.StatusOK, &respJSON)
return
case "webinfo":
service.Mutex.RLock()
respJSON, err := json.Marshal(service.WebInfo)
service.Mutex.RUnlock()
if err != nil {
writeJSONErrorResponse(&writer, err)
return
}
writeJSONResponse(&writer, http.StatusOK, &respJSON)
return
case "price":
service.Mutex.RLock()
respJSON, err := json.Marshal(service.PriceInfo)
service.Mutex.RUnlock()
if err != nil {
writeJSONErrorResponse(&writer, err)
return
}
writeJSONResponse(&writer, http.StatusOK, &respJSON)
return
default:
writer.WriteHeader(http.StatusNotFound)
return
}
}