-
Notifications
You must be signed in to change notification settings - Fork 5
/
indexer.go
689 lines (654 loc) · 21.6 KB
/
indexer.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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
package main
import (
"bytes"
"encoding/json"
"github.com/pokt-network/pocket-core/app/cmd/rpc"
"github.com/pokt-network/pocket-core/codec"
types3 "github.com/pokt-network/pocket-core/codec/types"
"github.com/pokt-network/pocket-core/crypto"
pc "github.com/pokt-network/pocket-core/types"
appTypes "github.com/pokt-network/pocket-core/x/apps/types"
"github.com/pokt-network/pocket-core/x/auth"
authTypes "github.com/pokt-network/pocket-core/x/auth"
"github.com/pokt-network/pocket-core/x/auth/types"
govTypes "github.com/pokt-network/pocket-core/x/gov"
nodeTypes "github.com/pokt-network/pocket-core/x/nodes/types"
pcTypes "github.com/pokt-network/pocket-core/x/pocketcore/types"
cryptoamino "github.com/tendermint/tendermint/crypto/encoding/amino"
coretypes "github.com/tendermint/tendermint/rpc/core/types"
"io/ioutil"
"log"
"math"
"net/http"
"strconv"
"strings"
"time"
)
//type Block coretypes.ResultBlock
const (
BlockTxsPath = "/query/blocktxs"
ClaimsPath = "/query/nodeclaims"
HeightPath = "/query/height"
BlockPath = "/query/block"
SupplyPath = "/query/supply"
UnitBlocks = "blocks"
UnitBlock = "block"
UnitB = "b"
UnitSessions = "sessions"
UnitSession = "session"
UnitS = "s"
UnitMinutes = "minutes"
UnitMinute = "minute"
UnitMin = "min"
UnitM = "m"
UnitHours = "hours"
UnitHour = "hour"
UnitHr = "hr"
UnitH = "h"
UnitDays = "days"
UnitDay = "day"
UnitD = "d"
UnitWeeks = "weeks"
UnitWeek = "week"
UnitW = "w"
)
var (
cdc = codec.NewCodec(types3.NewInterfaceRegistry())
)
func init() {
cdc.SetUpgradeOverride(false)
pc.RegisterCodec(cdc)
pcTypes.RegisterCodec(cdc)
authTypes.RegisterCodec(cdc)
nodeTypes.RegisterCodec(cdc)
appTypes.RegisterCodec(cdc)
govTypes.RegisterCodec(cdc)
crypto.RegisterAmino(cdc.AminoCodec().Amino)
cryptoamino.RegisterAmino(cdc.AminoCodec().Amino)
codec.RegisterEvidences(cdc.AminoCodec(), cdc.ProtoCodec())
}
type Timeline struct {
Start int64 `json:"start"`
End int64 `json:"end"`
Unit string `json:"unit"`
}
type ByBlock struct {
Start int64 `json:"start"`
End int64 `json:"end"`
}
type PaginatedHeightParams struct {
Height int64 `json:"height"`
Page int `json:"page,omitempty"`
PerPage int `json:"per_page,omitempty"`
Prove bool `json:"prove,omitempty"`
Sort string `json:"order,omitempty"`
}
type ClaimsRPCResponse struct {
Claims []pcTypes.MsgClaim `json:"result"`
Total int `json:"total_pages"`
Page int `json:"page"`
}
type HeightRPCResponse struct {
Height int64 `json:"height"`
}
type SupplyRPCResponse struct {
Total string `json:"total"`
}
type BlockReport struct {
MinHeight int64 `json:"min_height"`
MaxHeight int64 `json:"max_height"`
}
type Report struct {
TotalRelaysCompleted int64 `json:"total_relays_completed"`
TotalChallengesCompleted int64 `json:"total_challenges_completed"`
TotalMinted int64 `json:"total_minted"`
TotalGoodTxs int64 `json:"total_good_txs"`
TotalBadTxs int64 `json:"total_bad_txs"`
TotalProofTxs int64 `json:"proof_msgs"`
BadTxsMap map[uint32]int64 `json:"bad_txs_count_by_error"`
NodeReports map[string]NodeReport `json:"node_report"`
AppReports map[string]AppReport `json:"app_report"`
BlockSelector string `json:"selector"`
BlockReport BlockReport `json:"block_report"`
}
type ServiceReport struct {
Address string `json:"address"`
TotalRelays int64 `json:"total_relays"`
ChainID string `json:"relay_chain"`
}
type NodeReport struct {
Service []ServiceReport `json:"serviced"`
TotalRelays int64 `json:"total_relays"`
ServiceReportByChain map[string]int64 `json:"service_by_chain"`
}
type AppReport struct {
ServicedBy []ServiceReport `json:"serviced_by"`
TotalRelays int64 `json:"total_relays"`
ServicedReportByChain map[string]int64 `json:"serviced_by_chain"`
}
type ClaimsMap map[int64][]pcTypes.MsgClaim
type BlockTxsMap map[int64]rpc.RPCResultTxSearch
func ConvertTimelineToHeights(config Config) (blockReport BlockReport, err error) {
// start and end are negative values
var startInBlocks, endInBlocks, minHeight, maxHeight int64
var targetStartTime, targetEndTime time.Time
log.Println("Getting the latest height")
// get the latest height
latestheight, err := GetLatestHeight(config)
if err != nil {
return blockReport, err
}
log.Println("Getting the latest block")
block, err := GetBlock(latestheight, config)
if err != nil {
return blockReport, err
}
latestHeight := block.Block.Height
latestTime := block.Block.Time
log.Printf("Latest height is %d and latest time is: %s\n", latestHeight, latestTime.String())
switch strings.ToLower(config.Timeline.Unit) {
case UnitMinutes, UnitMinute, UnitMin, UnitM:
log.Println("Timeline unit is minutes")
targetStartTime, targetEndTime = GetTargetTimes(config, latestTime, time.Minute)
minHeight, maxHeight = GetClosestHeights(latestHeight, targetStartTime, latestTime, targetEndTime, config)
case UnitHours, UnitHour, UnitHr, UnitH:
log.Println("Timeline unit is hours")
targetStartTime, targetEndTime = GetTargetTimes(config, latestTime, time.Hour)
minHeight, maxHeight = GetClosestHeights(latestHeight, targetStartTime, latestTime, targetEndTime, config)
case UnitDays, UnitDay, UnitD:
log.Println("Timeline unit is days")
targetStartTime, targetEndTime = GetTargetTimes(config, latestTime, time.Hour*24)
minHeight, maxHeight = GetClosestHeights(latestHeight, targetStartTime, latestTime, targetEndTime, config)
case UnitWeeks, UnitWeek, UnitW:
log.Println("Timeline unit is weeks")
targetStartTime, targetEndTime = GetTargetTimes(config, latestTime, time.Hour*24*7)
minHeight, maxHeight = GetClosestHeights(latestHeight, targetStartTime, latestTime, targetEndTime, config)
case UnitBlocks, UnitBlock, UnitB:
log.Println("Timeline unit is blocks")
minHeight = latestHeight + config.Timeline.Start
maxHeight = latestHeight + config.Timeline.End
case UnitSessions, UnitSession, UnitS:
log.Println("Timeline unit is sessions")
startInBlocks = config.Timeline.Start * config.Params.BlocksPerSession
endInBlocks = config.Timeline.End * config.Params.BlocksPerSession
minHeight = latestHeight + startInBlocks
maxHeight = latestHeight + endInBlocks
default:
panic("ERROR: unrecognized unit: (minutes, hours, days, weeks, blocks)")
}
if minHeight < 0 {
err = NewInvalidMinimumHeightError(minHeight)
return
}
blockReport = BlockReport{
MinHeight: minHeight,
MaxHeight: maxHeight,
}
return
}
func GetChainData(minHeight, maxHeight int64, config Config) (blockTxsMap BlockTxsMap, claimsMap ClaimsMap, supplyStart, supplyEnd int) {
log.Println("Beginning Chain Data Operations")
count := 0
blockTxsMap = make(BlockTxsMap, 0)
claimsMap = make(ClaimsMap, 0)
// loop through all the heights and retrieve all the block-txs
log.Printf("Begin transactions / claims retrieval for heights: %d through %d\n", minHeight, maxHeight)
for height := minHeight; height < maxHeight; height++ {
if _, ok := blockTxsMap[height]; !ok {
result := rpc.RPCResultTxSearch{TotalCount: 1}
var err error
for page := 1; ; page++ {
result, err = GetBlockTx(height, page, config)
if err != nil {
if count >= config.HTTPRetry {
log.Fatalf("After %d retries, unable to get block-txs for height: %d at page %d with error: %s", config.HTTPRetry, height, page, err.Error())
} else {
log.Printf("RPC failure for blocktxs: %s. Trying to retry. Retry count is: %d/%d\n", err.Error(), count, config.HTTPRetry)
count++
page-- // try the same height again
result = rpc.RPCResultTxSearch{TotalCount: 1}
// arbitrary sleep to retry
time.Sleep(1 * time.Second)
continue
}
}
if result.TotalCount == 0 {
break
}
cur := blockTxsMap[height]
cur.TotalCount += result.TotalCount
cur.Txs = append(cur.Txs, result.Txs...)
blockTxsMap[height] = cur
count = 0
}
log.Printf("BlkTxs retrieved for height: %d, %d out of %d\n", height, height-minHeight, maxHeight-minHeight)
}
// skip claims for blocks 0 and 1
if height == 0 || height == 1 {
continue
}
// we want to check the claim at height - 1 cause the state = endBlockState
if _, ok := claimsMap[height]; !ok {
// get the claim for height-1
claimsResult, err := GetClaims(height-1, config)
if err != nil {
if count >= config.HTTPRetry {
log.Fatalf("After %d retries, unable to get claims for height: %d, with error: %s", config.HTTPRetry, height, err.Error())
} else {
log.Printf("RPC failure for claims: %s\nTrying to retry. Retry count is: %d/%d\n", err.Error(), count, config.HTTPRetry)
count++
height-- // try the same height again
// arbitrary sleep to retry
time.Sleep(5 * time.Second)
continue
}
} else {
log.Printf("Claims retrieved for height: %d, %d out of %d\n", height, height-minHeight, maxHeight-minHeight)
// add the block-txs to the result
claimsMap[height] = claimsResult
count = 0
}
}
}
log.Println("Getting starting supply")
// get the beginning and end supply
supplyStart, err := GetSupply(minHeight-1, config)
if err != nil {
log.Fatalf("unable to get the supply at height: %d with error %s", minHeight, err.Error())
}
log.Println("Getting ending supply")
supplyEnd, err = GetSupply(maxHeight-1, config)
if err != nil {
log.Fatalf("unable to get the supply at height: %d with error %s", maxHeight, err.Error())
}
return
}
func ProcessChainData(txsMap BlockTxsMap, claimsMap ClaimsMap, supplyStart, supplyEnd int, selector string, blockReport BlockReport) (result Report) {
log.Println("Chain Data Process Operation Started")
result = Report{
BadTxsMap: make(map[uint32]int64),
NodeReports: make(map[string]NodeReport, 0),
AppReports: make(map[string]AppReport, 0),
BlockSelector: selector,
BlockReport: blockReport,
}
log.Println("Looping through all of the block-txs and matching them with the corresponding claims")
for height, blockTx := range txsMap {
for _, txResult := range blockTx.Txs {
// check if bad transaction
if txResult.TxResult.Code != 0 {
log.Println("Bad tx found and logged")
result.TotalBadTxs++
result.BadTxsMap[txResult.TxResult.Code]++
continue
}
// log good tx
result.TotalGoodTxs++
// if not proofTx, continue on
if txResult.StdTx.Msg.Type() != pcTypes.MsgProofName {
log.Println("Good non-proof tx found and logged")
continue
}
// this is a proof msg
proofMsg, ok := txResult.StdTx.Msg.(pcTypes.MsgProof)
if !ok {
log.Fatalf(NewProofMsgInterfaceError().Error())
}
// log good tx
result.TotalProofTxs++
log.Println("Proof tx found and logged")
claim := pcTypes.MsgClaim{}
// find the corresponding claim
for _, c := range claimsMap[height] {
if !c.FromAddress.Equals(proofMsg.GetSigner()) {
continue
}
claim = c
}
if claim.FromAddress == nil {
log.Fatalf("No claim for valid proof object...")
}
log.Println("Corresponding claim found")
// check to see if claim is for relays
et := claim.EvidenceType
if et != pcTypes.RelayEvidence {
result.TotalChallengesCompleted++
continue
}
// get appAddress
appAddress := GetAddressFromPubKey(claim.SessionHeader.ApplicationPubKey)
nodeAddress := claim.FromAddress.String()
// get total # of relays
totalRelays := claim.TotalProofs
// get the relay chain id
chainID := claim.SessionHeader.Chain
// retrieve the app/node reports
appReport, found := result.AppReports[appAddress]
if !found {
log.Printf("New App report created for address %s\n", appAddress)
appReport = NewAppReport()
}
nodeReport, found := result.NodeReports[nodeAddress]
if !found {
log.Printf("New Node report created for address %s\n", nodeAddress)
nodeReport = NewNodeReport()
}
log.Printf("Adding data to the node report for address:%s\n", nodeAddress)
log.Printf("Adding data to the app report for address:%s\n", appAddress)
// add to the reports totals
appReport.TotalRelays += totalRelays
nodeReport.TotalRelays += totalRelays
// add to the chain statistics
appReport.ServicedReportByChain[chainID] += totalRelays
nodeReport.ServiceReportByChain[chainID] += totalRelays
result.TotalRelaysCompleted += totalRelays
// add an individual service report to the appReport
appReport.ServicedBy = append(appReport.ServicedBy, ServiceReport{
Address: nodeAddress,
TotalRelays: totalRelays,
ChainID: chainID,
})
// add an individual service report to the nodeReport
nodeReport.Service = append(nodeReport.Service, ServiceReport{
Address: appAddress,
TotalRelays: totalRelays,
ChainID: chainID,
})
// set the reports in the master report
result.AppReports[appAddress] = appReport
result.NodeReports[nodeAddress] = nodeReport
}
}
log.Println("Calculating the total minted")
// set the supply difference as total minted
result.TotalMinted = int64(supplyEnd - supplyStart)
log.Println("Report created")
return result
}
func NewAppReport() AppReport {
return AppReport{
ServicedBy: make([]ServiceReport, 0),
TotalRelays: 0,
ServicedReportByChain: make(map[string]int64),
}
}
func NewNodeReport() NodeReport {
return NodeReport{
Service: make([]ServiceReport, 0),
TotalRelays: 0,
ServiceReportByChain: make(map[string]int64),
}
}
func GetAddressFromPubKey(pkHex string) string {
apk, err := crypto.NewPublicKey(pkHex)
if err != nil {
log.Fatalf(NewPublicKeyError().Error())
}
return apk.Address().String()
}
func GetTargetTimes(config Config, latestTime time.Time, unit time.Duration) (targetStartTime, targetEndTime time.Time) {
log.Println("Calclating the approximate start and end times")
st := time.Duration(config.Timeline.Start) * unit
et := time.Duration(config.Timeline.End) * unit
targetStartTime = latestTime.Add(st)
targetEndTime = latestTime.Add(et)
log.Printf("Target start: %s\nTarget End: %s\n", targetStartTime.String(), targetEndTime.String())
return
}
func GetClosestHeights(latestHeight int64, targetStartTime, latestBlockTime, targetEndTime time.Time, config Config) (startHeight, endHeight int64) {
log.Println("Begin Closest Height Operations")
appxStartHeight := latestHeight - int64(latestBlockTime.Sub(targetStartTime).Minutes()/15)
appxEndHeight := latestHeight - int64(latestBlockTime.Sub(targetEndTime).Minutes()/15)
startHeight = BlockBinarySearch(targetStartTime, latestHeight, appxStartHeight, config)
log.Printf("Closest Start Height Found: %d\n", startHeight)
endHeight = BlockBinarySearch(targetEndTime, latestHeight, appxEndHeight, config)
log.Printf("Closest End Height Found: %d\n", endHeight)
return
}
func BlockBinarySearch(targetStartTime time.Time, latestHeight, tryHeight int64, config Config) (closestHeight int64) {
log.Printf("Performing a binary search for the closest height to the target time: %s\n", targetStartTime.String())
max := latestHeight
closestHeight = tryHeight
closestTime := time.Time{}
httpTryCount := 0
for min := int64(0); min < max && max-min != 1; {
log.Println("min: ", min, "max", max, "try height", tryHeight, "closest height", closestHeight)
// get the latest height
block, err := GetBlock(tryHeight, config)
// retry logic
if err != nil {
if httpTryCount >= config.HTTPRetry {
log.Fatalf("After %d retries, unable to get block for height: %d, with error: %s", config.HTTPRetry, tryHeight, err.Error())
} else {
log.Printf("RPC failure for block by height: %s\nTrying to retry. Retry count is: %d/%d\n", err.Error(), httpTryCount, config.HTTPRetry)
httpTryCount++
// arbitrary sleep to retry
time.Sleep(5 * time.Second)
continue
}
}
// if tryHeight block is before our target...
if block.Block.Time.Before(targetStartTime) {
// minimum is where the pivot was
min = tryHeight
} else {
// maximum is where the pivot was
max = tryHeight
}
// see if target height is closer than the current closest height
if IsCloserThan(block.Block.Time, closestTime, targetStartTime) {
// if is closer, let's update the closest
closestTime = block.Block.Time
closestHeight = block.Block.Height
}
// new pivot
tryHeight = (min + max) / 2
// reset the http try
httpTryCount = 0
}
return
}
func IsCloserThan(check, other, target time.Time) bool {
diff1 := math.Abs(float64(target.Sub(check).Nanoseconds()))
diff2 := math.Abs(float64(target.Sub(other).Nanoseconds()))
if diff1 >= diff2 {
return false
}
return true
}
func GetBlockTx(height int64, page int, config Config) (result rpc.RPCResultTxSearch, err error) {
requestBody := PaginatedHeightParams{
Height: height,
PerPage: 1000,
Page: page,
}
r, err := json.Marshal(requestBody)
if err != nil {
return result, err
}
req, err := http.NewRequest("POST", config.Endpoint+BlockTxsPath, bytes.NewBuffer(r))
if err != nil {
return result, err
}
c := http.Client{}
res, err := c.Do(req)
if err != nil {
return result, err
}
defer res.Body.Close()
bodyBz, err := ioutil.ReadAll(res.Body)
if err != nil {
return result, err
}
if res.StatusCode != 200 {
return result, NewHTTPStatusCode(res.StatusCode, string(bodyBz))
}
rts := &coretypes.ResultTxSearch{}
err = json.Unmarshal(bodyBz, &rts)
if err != nil {
return result, err
}
result = ResultTxSearchToRPC(rts)
return result, err
}
func GetClaims(height int64, config Config) (result []pcTypes.MsgClaim, err error) {
requestBody := PaginatedHeightParams{
Height: height,
PerPage: 10000, // TODO will fail if over 10K claims in 1 block
}
r, err := json.Marshal(requestBody)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", config.Endpoint+ClaimsPath, bytes.NewBuffer(r))
if err != nil {
return nil, err
}
c := http.Client{}
res, err := c.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
bodyBz, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
if res.StatusCode != 200 {
return nil, NewHTTPStatusCode(res.StatusCode, string(bodyBz))
}
state := ClaimsRPCResponse{}
err = json.Unmarshal(bodyBz, &state)
return state.Claims, err
}
func GetLatestHeight(config Config) (int64, error) {
req, err := http.NewRequest("POST", config.Endpoint+HeightPath, nil)
if err != nil {
return 0, err
}
c := http.Client{}
res, err := c.Do(req)
if err != nil {
return 0, err
}
defer res.Body.Close()
bodyBz, err := ioutil.ReadAll(res.Body)
if err != nil {
return 0, err
}
if res.StatusCode != 200 {
return 0, NewHTTPStatusCode(res.StatusCode, string(bodyBz))
}
height := HeightRPCResponse{}
err = json.Unmarshal(bodyBz, &height)
return height.Height, err
}
func GetBlock(height int64, config Config) (block *coretypes.ResultBlock, err error) {
requestBody := PaginatedHeightParams{Height: height}
r, err := json.Marshal(requestBody)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", config.Endpoint+BlockPath, bytes.NewBuffer(r))
if err != nil {
return nil, err
}
c := http.Client{}
res, err := c.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
bodyBz, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
if res.StatusCode != 200 {
return nil, NewHTTPStatusCode(res.StatusCode, string(bodyBz))
}
err = cdc.UnmarshalJSON(bodyBz, &block)
return
}
func GetSupply(height int64, config Config) (supply int, err error) {
requestBody := PaginatedHeightParams{Height: height}
r, err := json.Marshal(requestBody)
if err != nil {
return 0, err
}
req, err := http.NewRequest("POST", config.Endpoint+SupplyPath, bytes.NewBuffer(r))
if err != nil {
return 0, err
}
c := http.Client{}
res, err := c.Do(req)
if err != nil {
return 0, err
}
defer res.Body.Close()
bodyBz, err := ioutil.ReadAll(res.Body)
if err != nil {
return 0, err
}
if res.StatusCode != 200 {
return 0, NewHTTPStatusCode(res.StatusCode, string(bodyBz))
}
s := SupplyRPCResponse{}
err = cdc.UnmarshalJSON(bodyBz, &s)
if err != nil {
return 0, err
}
supply, err = strconv.Atoi(s.Total)
return
}
func ResultTxSearchToRPC(res *coretypes.ResultTxSearch) rpc.RPCResultTxSearch {
if res == nil {
return rpc.RPCResultTxSearch{}
}
rpcTxSearch := rpc.RPCResultTxSearch{
Txs: make([]*rpc.RPCResultTx, 0, res.TotalCount),
TotalCount: res.TotalCount,
}
for _, result := range res.Txs {
rpcTxSearch.Txs = append(rpcTxSearch.Txs, ResultTxToRPC(result))
}
return rpcTxSearch
}
func ResultTxToRPC(res *coretypes.ResultTx) *rpc.RPCResultTx {
if res == nil {
return nil
}
tx := UnmarshalTx(res.Tx, res.Height)
//if app.GlobalConfig.PocketConfig.DisableTxEvents {
res.TxResult.Events = nil
//}
rpcDeliverTx := rpc.RPCResponseDeliverTx{
Code: res.TxResult.Code,
Data: res.TxResult.Data,
Log: res.TxResult.Log,
Info: res.TxResult.Info,
Events: res.TxResult.Events,
Codespace: res.TxResult.Codespace,
Signer: res.TxResult.Signer,
Recipient: res.TxResult.Recipient,
MessageType: res.TxResult.MessageType,
}
rpcStdTx := rpc.RPCStdTx(tx)
r := &rpc.RPCResultTx{
Hash: res.Hash,
Height: res.Height,
Index: res.Index,
TxResult: rpcDeliverTx,
Tx: res.Tx,
Proof: res.Proof,
StdTx: rpcStdTx,
}
return r
}
func UnmarshalTx(txBytes []byte, height int64) types.StdTx {
defaultTxDecoder := auth.DefaultTxDecoder(cdc)
tx, err := defaultTxDecoder(txBytes, height)
if err != nil {
log.Fatalf("Could not decode transaction: " + err.Error())
}
return tx.(auth.StdTx)
}