-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
819 lines (685 loc) · 20.7 KB
/
main.go
File metadata and controls
819 lines (685 loc) · 20.7 KB
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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
package main
import (
"bytes"
"database/sql"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
)
var c conf
var mutex = &sync.Mutex{}
type blockInformation struct {
Time int
Height int
TxID string
Hash string
Addr string
Coins float64
}
var blockMap = make(map[int]blockInformation)
type pogoInfoForAddr struct {
lastUpdate int64
coinsAtTimes map[int64]float64
}
// Key is a receiving addr
var pogoCoins = make(map[string]pogoInfoForAddr)
var db *sql.DB
var dbErr error
var currentHeight int
var currentDBHeight int
var lowestDBHeight int
var blockHistoryDepth int
var globalNetHash float64
func main() {
gin.SetMode(gin.ReleaseMode)
router := gin.Default()
c.getConf()
currentDBHeight = 0
lowestDBHeight = 5000000000
globalNetHash = 0.0
blockHistoryDepth = 100000
db, dbErr = sql.Open("mysql", c.ServiceDBUser+":"+c.ServiceDBPass+"@tcp("+c.ServiceDBIP+":"+c.ServiceDBPort+")/"+c.ServiceDBName)
// Truly a fatal error.
if dbErr != nil {
panic(dbErr.Error())
}
defer db.Close()
fmt.Printf("Connected to DB: %s\n", c.ServiceDBName)
getDBHeight()
currentHeight, err := getCurrentHeight()
if err != nil {
fmt.Printf("Unable to connect to node, using DB cache only, height %d: Error %s", currentDBHeight, err)
currentHeight = currentDBHeight
}
fmt.Printf("Current block height from node: %d\n", currentHeight)
fmt.Printf("Initializing...\n")
fmt.Printf("Loading new blocks from DB...\n")
updateStats()
fmt.Printf("Lowest DB height is %d", lowestDBHeight)
fmt.Printf("Highest DB height is %d", currentDBHeight)
fmt.Printf("Done loading new blocks from DB!\n")
fmt.Printf("Caching DB to memory...\n")
loadDBStatsToMemory()
fmt.Printf("DB cache to memory complete!\n")
// Grab new block info from the node every minute
go func() {
fmt.Printf("Service is RUNNING on port %s\n", c.ServicePort)
for {
time.Sleep(60 * time.Second)
updateStats()
}
}()
router.GET("/getminingstats", getAddrMiningStatsRPC)
err = router.Run(":" + c.ServicePort)
if err != nil {
log.Fatalf("Unable to start router: %s", err)
}
}
func getDBHeight() {
type DBResult struct {
HeightID int `json:"height_id"`
}
results, err := db.Query("select height_id from stats order by height_id desc limit 0,1")
// Fatal, we need our DB
if err != nil {
panic(err.Error())
}
for results.Next() {
var dbResult DBResult
err = results.Scan(&dbResult.HeightID)
if err != nil {
panic(err.Error())
}
currentDBHeight = dbResult.HeightID
}
}
func loadDBStatsToMemory() {
type DBResult struct {
HeightID int `json:"height_id"`
Blockhash string `json:"blockhash"`
Epoch int `json:"epoch"`
Coins float64 `json:"coins"`
Miningaddr string `json:"miningaddr"`
}
results, err := db.Query("select height_id, blockhash, epoch, coins, miningaddr from stats")
if err != nil {
panic(err.Error())
}
for results.Next() {
var dbResult DBResult
err = results.Scan(&dbResult.HeightID, &dbResult.Blockhash, &dbResult.Epoch, &dbResult.Coins, &dbResult.Miningaddr)
if err != nil {
panic(err.Error())
}
var myStatResult blockInformation
myStatResult.Addr = dbResult.Miningaddr
myStatResult.Coins = dbResult.Coins
myStatResult.Height = dbResult.HeightID
myStatResult.Hash = dbResult.Blockhash
myStatResult.Time = dbResult.Epoch
mutex.Lock()
blockMap[dbResult.HeightID] = myStatResult
mutex.Unlock()
}
}
// ALL TIMES IN UTC
func getDayStart(dayOffset int, loc *time.Location) int64 {
myTime := time.Now().In(loc)
myTime = myTime.AddDate(0, 0, dayOffset)
return time.Date(myTime.Year(), myTime.Month(), myTime.Day(), 0, 0, 0, 0, loc).Unix()
}
func getHourStart(hourOffset int, loc *time.Location) int64 {
myTime := time.Now().In(loc)
myTime = myTime.Add(time.Hour * time.Duration(hourOffset))
return time.Date(myTime.Year(), myTime.Month(), myTime.Day(), myTime.Hour(), 0, 0, 0, loc).Unix()
}
func getCurrentHour(loc *time.Location) int {
myTime := time.Now().In(loc)
return myTime.Hour()
}
// Make RPC to POGO and update pogoCoins
func getPogoInfoForAddr(addr string, loc *time.Location) {
startEpoch := getHourStart(0, loc) + 60 // Wait 1 minute past the hour to get new data from POGO...
curEpoch := time.Now().In(loc).Unix()
if curVal, ok := pogoCoins[addr]; ok {
if curVal.lastUpdate > startEpoch && (curEpoch-curVal.lastUpdate) < 600 {
fmt.Printf("No need to get new info from POGO!\n")
return
}
}
fmt.Printf("Getting new info from POGO!\n")
var newPogoInfoForAddr pogoInfoForAddr
var newCoinsAtTimes = make(map[int64]float64)
newPogoInfoForAddr.coinsAtTimes = newCoinsAtTimes
newPogoInfoForAddr.lastUpdate = time.Now().Unix()
mutex.Lock()
pogoCoins[addr] = newPogoInfoForAddr
type PogoResp struct {
Combined struct {
UnpaidBalanceAtoms int `json:"UnpaidBalanceAtoms"`
RecentPayouts []struct {
CreatedAt int `json:"CreatedAt"`
Atoms int `json:"Atoms"`
} `json:"RecentPayouts"`
} `json:"combined"`
}
var thisPogo PogoResp
reqUrl := url.URL{
Scheme: "https",
Host: "pogo.dmo-tools.com",
Path: "api/v1/stats/" + addr,
}
resp, err := http.Get(reqUrl.String())
if err != nil {
log.Printf("Unable to make request to dmo-tools: %s", err.Error())
mutex.Unlock()
return
}
bodyText, err := io.ReadAll(resp.Body)
if err != nil {
log.Printf("Unable to make request to dmo-tools: %s", err.Error())
mutex.Unlock()
return
}
if err := json.Unmarshal(bodyText, &thisPogo); err != nil {
log.Printf("Unable to make request to dmo-statservice: %s", err.Error())
mutex.Unlock()
return
}
for _, payout := range thisPogo.Combined.RecentPayouts {
pogoCoins[addr].coinsAtTimes[int64(payout.CreatedAt)] = float64(payout.Atoms) / 100000000
}
pogoCoins[addr].coinsAtTimes[curEpoch] = float64(thisPogo.Combined.UnpaidBalanceAtoms) / 100000000
mutex.Unlock()
}
// Load blocks from node up to current block. Do not expose RPC server until this is done. Display some output to user
func updateStats() {
var err error
currentHeight, err = getCurrentHeight()
var noNode = false
if err != nil {
currentHeight = currentDBHeight
fmt.Printf("Unable to connect to node, using cached DB data\n")
noNode = true
} else {
fmt.Printf("Current block height from node: %d\n", currentHeight)
}
type DBResult struct {
HeightID int `json:"height_id"`
}
getDBHeight()
results, err := db.Query("select height_id from stats order by height_id asc limit 0,1")
if err != nil {
panic(err.Error())
}
for results.Next() {
var dbResult DBResult
err = results.Scan(&dbResult.HeightID)
if err != nil {
panic(err.Error()) // proper error handling instead of panic in your app
}
lowestDBHeight = dbResult.HeightID
}
var startHeight = currentDBHeight
if startHeight < (currentHeight - blockHistoryDepth) {
startHeight = currentHeight - blockHistoryDepth
} else {
startHeight = currentDBHeight + 1
}
if noNode {
return
}
netHash, err2 := getCurrentNethash()
if err2 == nil {
globalNetHash = netHash
}
blockIDToGet := startHeight
fmt.Printf("Grabbing %d new blocks from node...\n", currentHeight-blockIDToGet)
var myBlockInfo blockInformation
for blockIDToGet < currentHeight {
myBlockInfo = getFullBlockInfoForHeight(blockIDToGet)
mutex.Lock()
blockMap[myBlockInfo.Height] = myBlockInfo // Add to memory cache
mutex.Unlock()
insert, err := db.Query(`
INSERT INTO stats (height_id, blockhash, epoch, coins, miningaddr) VALUES (?, ?, ?, ?, ?)`,
blockIDToGet, myBlockInfo.Hash, myBlockInfo.Time, myBlockInfo.Coins, myBlockInfo.Addr)
if err != nil {
panic(err.Error())
}
insert.Close()
blockIDToGet++
if (blockIDToGet % 500) == 0 {
fmt.Printf("Grabbed up to block id %d\n", blockIDToGet)
}
}
fmt.Printf("DB update from Node is complete!\n")
}
type mineRPC struct {
Addresses string
NumDays int
TimeZone string
}
func contains(s []string, str string) bool {
for _, v := range s {
if v == str {
return true
}
}
return false
}
/* Accept json request like:
{
"Addresses": "dy1qpfr5yhdkgs6jyuk945y23pskdxmy9ajefczsvm,kljdsalkjsadlksajd",
}
*/
// TODO: Do not allow more than 10 receiving addresses
// For each addr, call getPogoInfoForAddr if the last time it was updated for that addr is before the beginning of the current hour
// When adding up coin counts, include the pogo info.
func getAddrMiningStatsRPC(c *gin.Context) {
var jsonBody mineRPC
if err := c.BindJSON(&jsonBody); err != nil {
fmt.Printf("Got unhandled (bad) request!")
return
}
type HourStat struct {
Hour int
Coins float64
ChainCoins float64
WinPercent float64
}
var hourStats []HourStat
ipFrom := c.ClientIP()
fmt.Printf("Request from %s: Getting stats for addresse(s) %s\n", ipFrom, jsonBody.Addresses)
// load time zone
if jsonBody.TimeZone == "" {
jsonBody.TimeZone = "UTC"
}
loc, e := time.LoadLocation(jsonBody.TimeZone)
if e != nil {
fmt.Printf("Unable to get location for tz: %s\n", e.Error())
loc, _ = time.LoadLocation("UTC") // This should always work...
}
addrsToCheck := strings.Split(jsonBody.Addresses, ",")
for i := 0; i < len(addrsToCheck); i++ {
getPogoInfoForAddr(addrsToCheck[i], loc)
}
hoursToday := getCurrentHour(loc)
for i := 0; i <= hoursToday; i++ {
curHour := i - hoursToday
startEpoch := getHourStart(curHour, loc)
endEpoch := startEpoch + 3600
var thisHour HourStat
thisHour.Coins = getCoinsInEpochRange(startEpoch, endEpoch, jsonBody.Addresses)
thisHour.ChainCoins = getCoinsInEpochRange(startEpoch, endEpoch, "")
if thisHour.Coins > 0.1 && thisHour.ChainCoins > 0.1 {
thisHour.WinPercent = thisHour.Coins * 100.0 / thisHour.ChainCoins
} else {
thisHour.WinPercent = 0.0
}
thisHour.Hour = i
hourStats = append(hourStats, thisHour)
}
type DayStat struct {
Day string
Coins float64
ChainCoins float64
WinPercent float64
}
var dayStats []DayStat
numDays := jsonBody.NumDays
if numDays < 2 {
numDays = 2
}
if numDays > 21 {
numDays = 21
}
for i := 0; i <= numDays; i++ {
curDay := i - numDays
startEpoch := getDayStart(curDay, loc)
endEpoch := startEpoch + 86400
var thisDay DayStat
thisDay.Coins = getCoinsInEpochRange(startEpoch, endEpoch, jsonBody.Addresses)
thisDay.ChainCoins = getCoinsInEpochRange(startEpoch, endEpoch, "")
if thisDay.Coins > 0.1 && thisDay.ChainCoins > 0.1 {
thisDay.WinPercent = thisDay.Coins * 100.0 / thisDay.ChainCoins
} else {
thisDay.WinPercent = 0.0
}
formattedTime := time.Unix(startEpoch, 0).In(loc).Format("2006-01-02")
if i < numDays {
thisDay.Day = formattedTime
} else {
thisDay.Day = "Today"
}
dayStats = append(dayStats, thisDay)
}
type ResponseStats struct {
HourlyStats []HourStat
DailyStats []DayStat
ProjectedCoinsToday float64
NetHash float64
}
secondsSoFarToday := float64(time.Now().Unix()-getDayStart(0, loc)) + 1.0
var thisResponse ResponseStats
thisResponse.NetHash = globalNetHash
thisResponse.ProjectedCoinsToday = dayStats[len(dayStats)-1].Coins * (86400.0 / secondsSoFarToday)
thisResponse.HourlyStats = hourStats
thisResponse.DailyStats = dayStats
c.JSON(200, thisResponse)
}
// Get lowest and highest block for epoch range
func findBlocksForEpochRange(startEpoch int64, endEpoch int64) (int, int) {
lowest := lowestDBHeight
highest := currentDBHeight
found := 0
for found == 0 {
if blockMap[lowest].Time > int(startEpoch) || lowest > currentDBHeight {
lowest -= 512
found = 1
}
lowest += 256
}
found = 0
for found == 0 {
if blockMap[highest].Time < int(endEpoch) || highest < lowestDBHeight {
highest += 512
found = 1
}
highest -= 256
}
if lowest < lowestDBHeight {
lowest = lowestDBHeight
}
if highest > currentDBHeight {
highest = currentDBHeight
}
return lowest, highest
}
// Get the number of coins in a given epoch range. If addresses is passed, limit count to coins
// for those addresses. If not then just get all mined coins in range count...
func getCoinsInEpochRange(startEpoch int64, endEpoch int64, addresses string) float64 {
addrsToCheck := strings.Split(addresses, ",")
numCoins := 0.0
lowest, highest := findBlocksForEpochRange(startEpoch, endEpoch)
// Add POGO counts for this epoch range here
for j := 0; j < len(addrsToCheck); j++ {
for pogoEpoch, coins := range pogoCoins[addrsToCheck[j]].coinsAtTimes {
// Shift the payout time back by 1 minute so it falls into the previous hour since it was
// coins paid out FOR the previous hour.
pogoEpoch -= 60
if startEpoch <= pogoEpoch && pogoEpoch < endEpoch {
numCoins += coins
}
}
}
for i := lowest; i < highest; i++ {
if block, ok := blockMap[i]; ok {
if len(addrsToCheck) > 0 && len(addrsToCheck[0]) > 0 {
if contains(addrsToCheck, block.Addr) {
if startEpoch < int64(block.Time) && int64(block.Time) < endEpoch {
numCoins += block.Coins
}
}
} else {
if startEpoch < int64(block.Time) && int64(block.Time) < endEpoch {
numCoins += block.Coins
}
}
}
}
return numCoins
}
func getFullBlockInfoForHeight(height int) blockInformation {
var myBlockInfo blockInformation
myBlockInfo.Height = height
myBlockInfo = getBlockHash(myBlockInfo)
myBlockInfo = getBlock(myBlockInfo)
myBlockInfo = getTransInfo(myBlockInfo)
return myBlockInfo
}
func getCurrentNethash() (float64, error) {
type netHashResult struct {
Result float64 `json:"result"`
}
client := &http.Client{
Timeout: 5 * time.Second,
}
reqURL := url.URL{
Scheme: "http",
Host: c.NodeIP + ":" + c.NodePort,
Path: "",
}
var data = bytes.NewBufferString(`{"id": 1,"method": "getnetworkhashps","params": {"nblocks": 100}}`)
req, err := http.NewRequest("POST", reqURL.String(), data)
if err != nil {
return 0, err
}
req.SetBasicAuth(c.NodeUser, c.NodePass)
resp, err := client.Do(req)
if err != nil {
return 0, err
}
bodyText, err := io.ReadAll(resp.Body)
if err != nil {
return 0, err
}
var myNetHash netHashResult
if err := json.Unmarshal(bodyText, &myNetHash); err != nil {
return 0, err
}
return myNetHash.Result, nil
}
func getCurrentHeight() (int, error) {
type blockHeightResult struct {
ID string `json:"id"`
Result int `json:"result"`
}
client := &http.Client{
Timeout: 5 * time.Second,
}
reqURL := url.URL{
Scheme: "http",
Host: c.NodeIP + ":" + c.NodePort,
Path: "",
}
var data = bytes.NewBufferString(`{"jsonrpc":"1.0","id":"curltest","method":"getblockcount", "params": { }}`)
req, err := http.NewRequest("POST", reqURL.String(), data)
if err != nil {
return 0, err
}
req.SetBasicAuth(c.NodeUser, c.NodePass)
resp, err := client.Do(req)
if err != nil {
return 0, err
}
bodyText, err := io.ReadAll(resp.Body)
if err != nil {
return 0, err
}
var myBlockHeight blockHeightResult
if err := json.Unmarshal(bodyText, &myBlockHeight); err != nil {
return 0, err
}
return myBlockHeight.Result, nil
}
// Step one, get the block hash for the block number
func getBlockHash(blockInfo blockInformation) blockInformation {
type blockHashResult struct {
ID string `json:"id"`
Result string `json:"result"`
}
client := &http.Client{}
reqURL := url.URL{
Scheme: "http",
Host: c.NodeIP + ":" + c.NodePort,
Path: "",
}
var data = bytes.NewBufferString(`{"jsonrpc":"1.0","id":"curltest","method":"getblockhash", "params": { "height": ` + strconv.Itoa(blockInfo.Height) + `}}`)
req, err := http.NewRequest("POST", reqURL.String(), data)
if err != nil {
log.Fatalf("Unable to construct getblockhash request to %q: %s", reqURL.String(), err)
}
req.SetBasicAuth(c.NodeUser, c.NodePass)
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
return blockInfo
}
bodyText, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Unable to read response body for getblockhash request: %s", err)
}
var myBlockHash blockHashResult
if err := json.Unmarshal(bodyText, &myBlockHash); err != nil {
return blockInfo
}
blockInfo.Hash = myBlockHash.Result
return blockInfo
}
// Step two, get the block for the hash... returns a txid IF IT WAS A MINED BLOCK
func getBlock(blockInfo blockInformation) blockInformation {
type blockResult struct {
Result struct {
Hash string `json:"hash"`
Confirmations int `json:"confirmations"`
Height int `json:"height"`
Version int `json:"version"`
VersionHex string `json:"versionHex"`
Merkleroot string `json:"merkleroot"`
Time int `json:"time"`
Mediantime int `json:"mediantime"`
Nonce int `json:"nonce"`
Bits string `json:"bits"`
Difficulty float64 `json:"difficulty"`
Chainwork string `json:"chainwork"`
NTx int `json:"nTx"`
Previousblockhash string `json:"previousblockhash"`
Nextblockhash string `json:"nextblockhash"`
Strippedsize int `json:"strippedsize"`
Size int `json:"size"`
Weight int `json:"weight"`
Tx []string `json:"tx"`
} `json:"result"`
Error interface{} `json:"error"`
ID string `json:"id"`
}
client := &http.Client{}
reqURL := url.URL{
Scheme: "http",
Host: c.NodeIP + ":" + c.NodePort,
Path: "",
}
var data = bytes.NewBufferString(`{"jsonrpc":"1.0","id":"curltest","method":"getblock", "params": { "blockhash": "` + blockInfo.Hash + `"}}`)
req, err := http.NewRequest("POST", reqURL.String(), data)
if err != nil {
log.Fatalf("Unable to construct getblock request to %q: %s", reqURL.String(), err)
}
req.SetBasicAuth(c.NodeUser, c.NodePass)
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
return blockInfo
}
bodyText, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Unable to read response body for getblock request: %s", err)
}
var myBlock blockResult
if err := json.Unmarshal(bodyText, &myBlock); err != nil {
return blockInfo
}
blockInfo.Time = myBlock.Result.Time
blockInfo.TxID = myBlock.Result.Tx[0]
return blockInfo
}
type minedTxInfo struct {
miningAddr string
coins float64
}
// Step three, get the information I care about
func getTransInfo(blockInfo blockInformation) blockInformation {
var myInfo minedTxInfo
myInfo.miningAddr = "professorminingaddr"
myInfo.coins = 1.001
type TransResponse struct {
Result struct {
InActiveChain bool `json:"in_active_chain"`
Txid string `json:"txid"`
Hash string `json:"hash"`
Version int `json:"version"`
Size int `json:"size"`
Vsize int `json:"vsize"`
Weight int `json:"weight"`
Locktime int `json:"locktime"`
Vin []struct {
Coinbase string `json:"coinbase"`
Txinwitness []string `json:"txinwitness"`
Sequence int64 `json:"sequence"`
} `json:"vin"`
Vout []struct {
Value float64 `json:"value"`
N int `json:"n"`
ScriptPubKey struct {
Asm string `json:"asm"`
Hex string `json:"hex"`
Address string `json:"address"`
Type string `json:"type"`
} `json:"scriptPubKey,omitempty"`
} `json:"vout"`
Hex string `json:"hex"`
Blockhash string `json:"blockhash"`
Confirmations int `json:"confirmations"`
Time int `json:"time"`
Blocktime int `json:"blocktime"`
} `json:"result"`
Error interface{} `json:"error"`
ID string `json:"id"`
}
client := &http.Client{}
reqURL := url.URL{
Scheme: "http",
Host: c.NodeIP + ":" + c.NodePort,
Path: "",
}
var data = bytes.NewBufferString(`{"jsonrpc":"1.0","id":"curltest","method":"getrawtransaction", "params": { "blockhash": "` + blockInfo.Hash + `", "txid": "` + blockInfo.TxID + `", "verbose": true}}`)
req, err := http.NewRequest("POST", reqURL.String(), data)
if err != nil {
log.Fatalf("Unable to construct getrawtransaction request to %q: %s", reqURL.String(), err)
}
req.SetBasicAuth(c.NodeUser, c.NodePass)
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
return blockInfo
}
bodyText, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Unable to read getrawtransaction body: %s", err)
}
//fmt.Printf("Raw trans info: %s\n", bodyText)
var myTrans TransResponse
if err := json.Unmarshal(bodyText, &myTrans); err != nil {
return blockInfo
}
if myTrans.Result.Vout[0].Value > 2.0 {
fmt.Printf("Coinbase value %s, coins %.2f\n", myTrans.Result.Vin[0].Coinbase, myTrans.Result.Vout[0].Value)
}
blockInfo.Addr = myTrans.Result.Vout[0].ScriptPubKey.Address
// TODO: CHECK THIS, will non-mine transactions just have no string here?
if len(myTrans.Result.Vin[0].Coinbase) > 0 {
blockInfo.Coins = myTrans.Result.Vout[0].Value
} else {
blockInfo.Coins = 0.0 // If it wasn't a MINED transaction, don't count the coins!
}
return blockInfo
}