-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathredis.go
2482 lines (2144 loc) · 73.6 KB
/
redis.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
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
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package storage
import (
"fmt"
"math"
"math/big"
"net/smtp"
"sort"
"strconv"
"strings"
"time"
"log"
"github.com/yuriy0803/open-etc-pool-friends/util"
"gopkg.in/redis.v3"
)
type Config struct {
SentinelEnabled bool `json:"sentinelEnabled"`
Endpoint string `json:"endpoint"`
Password string `json:"password"`
Database int64 `json:"database"`
PoolSize int `json:"poolSize"`
MasterName string `json:"masterName"`
SentinelAddrs []string `json:"sentinelAddrs"`
}
type RedisClient struct {
client *redis.Client
prefix string
pplns int64
CoinName string
prefixSolo string
}
type SumRewardData struct {
Interval int64 `json:"inverval"`
Reward int64 `json:"reward"`
Name string `json:"name"`
Offset int64 `json:"offset"`
Blocks int64 `json:"blocks"`
Effort float64 `json:"averageLuck"`
Count float64 `json:"_"`
ESum float64 `json:"_"`
}
type RewardData struct {
Height int64 `json:"blockheight"`
Timestamp int64 `json:"timestamp"`
BlockHash string `json:"blockhash"`
Reward int64 `json:"reward"`
Percent float64 `json:"percent"`
Immature bool `json:"immature"`
Difficulty int64 `json:"-"`
PersonalShares int64 `json:"-"`
PersonalEffort float64 `json:"personalLuck"`
}
type BlockData struct {
Height int64 `json:"height"`
Timestamp int64 `json:"timestamp"`
Difficulty int64 `json:"difficulty"`
TotalShares int64 `json:"shares"`
PersonalShares int64 `json:"PersonalShares"`
Uncle bool `json:"uncle"`
UncleHeight int64 `json:"uncleHeight"`
Orphan bool `json:"orphan"`
Hash string `json:"hash"`
Finder string `json:"finder"`
Worker string `json:"worker"`
Nonce string `json:"-"`
PowHash string `json:"-"`
MixDigest string `json:"-"`
Reward *big.Int `json:"-"`
ExtraReward *big.Int `json:"-"`
ImmatureReward string `json:"-"`
RewardString string `json:"reward"`
RoundHeight int64 `json:"-"`
candidateKey string
immatureKey string
MiningType string `json:"miningType"`
ShareDiffCalc int64 `json:"shareDiff"`
}
type PoolCharts struct {
Timestamp int64 `json:"x"`
TimeFormat string `json:"timeFormat"`
PoolHash int64 `json:"y"`
}
type MinerCharts struct {
Timestamp int64 `json:"x"`
TimeFormat string `json:"timeFormat"`
MinerHash int64 `json:"minerHash"`
MinerLargeHash int64 `json:"minerLargeHash"`
WorkerOnline string `json:"workerOnline"`
}
type NetCharts struct {
Timestamp int64 `json:"x"`
TimeFormat string `json:"timeFormat"`
NetHash int64 `json:"y"`
}
type ShareCharts struct {
Timestamp int64 `json:"x"`
TimeFormat string `json:"timeFormat"`
Valid int64 `json:"valid"`
Stale int64 `json:"stale"`
WorkerOnline string `json:"workerOnline"`
}
type PaymentCharts struct {
Timestamp int64 `json:"x"`
TimeFormat string `json:"timeFormat"`
Amount int64 `json:"amount"`
}
type LuckCharts struct {
Timestamp int64 `json:"x"`
Height int64 `json:"height"`
Difficulty int64 `json:"difficulty"`
Shares int64 `json:"shares"`
SharesDiff float64 `json:"sharesDiff"`
Reward string `json:"reward"`
}
func (b *BlockData) RewardInShannon() int64 {
reward := new(big.Int).Div(b.Reward, util.Shannon)
return reward.Int64()
}
func (b *BlockData) serializeHash() string {
if len(b.Hash) > 0 {
return b.Hash
} else {
return "0x0"
}
}
func (b *BlockData) RoundKey() string {
return join(b.RoundHeight, b.Hash)
}
func (b *BlockData) key() string {
return join(b.UncleHeight, b.Orphan, b.Nonce, b.serializeHash(), b.Timestamp, b.Difficulty, b.TotalShares, b.Finder, b.Reward, b.Worker, b.MiningType, b.ShareDiffCalc, b.PersonalShares)
}
type Miner struct {
LastBeat int64 `json:"lastBeat"`
HR int64 `json:"hr"`
Offline bool `json:"offline"`
Solo bool `json:"solo"`
startedAt int64
Blocks int64 `json:"blocks"`
}
type Worker struct {
Miner
TotalHR int64 `json:"hr2"`
PortDiff string `json:"portDiff"`
WorkerHostname string `json:"hostname"`
ValidShares int64 `json:"valid"`
StaleShares int64 `json:"stale"`
InvalidShares int64 `json:"invalid"`
ValidPercent float64 `json:"v_per"`
StalePercent float64 `json:"s_per"`
InvalidPercent float64 `json:"i_per"`
WorkerStatus int64 `json:"w_stat"`
WorkerStatushas int64 `json:"w_stat_s"`
}
func NewRedisClient(cfg *Config, prefix string, pplns int64, CoinName string, CoinSolo string) *RedisClient {
var client *redis.Client
if cfg.SentinelEnabled && len(cfg.MasterName) != 0 && len(cfg.SentinelAddrs) != 0 {
// sentinel mode
client = redis.NewFailoverClient(&redis.FailoverOptions{
MasterName: cfg.MasterName,
SentinelAddrs: cfg.SentinelAddrs,
Password: cfg.Password,
DB: cfg.Database,
PoolSize: cfg.PoolSize,
})
} else {
// single instance
client = redis.NewClient(&redis.Options{
Addr: cfg.Endpoint,
Password: cfg.Password,
DB: cfg.Database,
PoolSize: cfg.PoolSize,
})
}
return &RedisClient{client: client, prefix: prefix, pplns: pplns, CoinName: CoinName, prefixSolo: CoinSolo}
}
func (r *RedisClient) Client() *redis.Client {
return r.client
}
func (r *RedisClient) Check() (string, error) {
return r.client.Ping().Result()
}
func (r *RedisClient) BgSave() (string, error) {
return r.client.BgSave().Result()
}
// Always returns list of addresses. If Redis fails it will return empty list.
func (r *RedisClient) GetBlacklist() ([]string, error) {
cmd := r.client.SMembers(r.formatKey("blacklist"))
if cmd.Err() != nil {
return []string{}, cmd.Err()
}
return cmd.Val(), nil
}
// Always returns list of IPs. If Redis fails it will return empty list.
func (r *RedisClient) GetWhitelist() ([]string, error) {
cmd := r.client.SMembers(r.formatKey("whitelist"))
if cmd.Err() != nil {
return []string{}, cmd.Err()
}
return cmd.Val(), nil
}
func (r *RedisClient) WriteNodeState(id string, height uint64, diff *big.Int, blocktime float64) error {
tx := r.client.Multi()
defer tx.Close()
now := util.MakeTimestamp() / 1000
_, err := tx.Exec(func() error {
tx.HSet(r.formatKey("nodes"), join(id, "name"), id)
tx.HSet(r.formatKey("nodes"), join(id, "height"), strconv.FormatUint(height, 10))
tx.HSet(r.formatKey("nodes"), join(id, "difficulty"), diff.String())
tx.HSet(r.formatKey("nodes"), join(id, "lastBeat"), strconv.FormatInt(now, 10))
tx.HSet(r.formatKey("nodes"), join(id, "blocktime"), strconv.FormatFloat(blocktime, 'f', 4, 64))
return nil
})
return err
}
func (r *RedisClient) GetNodeStates() ([]map[string]interface{}, error) {
cmd := r.client.HGetAllMap(r.formatKey("nodes"))
if cmd.Err() != nil {
return nil, cmd.Err()
}
m := make(map[string]map[string]interface{})
for key, value := range cmd.Val() {
parts := strings.Split(key, ":")
if val, ok := m[parts[0]]; ok {
val[parts[1]] = value
} else {
node := make(map[string]interface{})
node[parts[1]] = value
m[parts[0]] = node
}
}
v := make([]map[string]interface{}, len(m), len(m))
i := 0
for _, value := range m {
v[i] = value
i++
}
return v, nil
}
func (r *RedisClient) checkPoWExist(height uint64, params []string) (bool, error) {
// Sweep PoW backlog for previous blocks, we have 3 templates back in RAM
r.client.ZRemRangeByScore(r.formatKey("pow"), "-inf", fmt.Sprint("(", height-8))
val, err := r.client.ZAdd(r.formatKey("pow"), redis.Z{Score: float64(height), Member: strings.Join(params, ":")}).Result()
return val == 0, err
}
func (r *RedisClient) WriteShare(login, id string, params []string, diff int64, shareDiffCalc int64, height uint64, window time.Duration, hostname string) (bool, error) {
exist, err := r.checkPoWExist(height, params)
if err != nil {
return false, err
}
// Duplicate share, (nonce, powHash, mixDigest) pair exist
if exist {
return true, nil
}
tx := r.client.Multi()
defer tx.Close()
ms := util.MakeTimestamp()
ts := ms / 1000
_, err = tx.Exec(func() error {
r.writeShare(tx, ms, ts, login, id, diff, shareDiffCalc, window, hostname)
tx.HIncrBy(r.formatKey("stats"), "roundShares", diff)
return nil
})
return false, err
}
func (r *RedisClient) WriteShareSolo(login, id string, params []string, diff int64, shareDiffCalc int64, height uint64, window time.Duration, hostname string) (bool, error) {
exist, err := r.checkPoWExist(height, params)
if err != nil {
return false, err
}
// Duplicate share, (nonce, powHash, mixDigest) pair exist
if exist {
return true, nil
}
tx := r.client.Multi()
defer tx.Close()
ms := util.MakeTimestamp()
ts := ms / 1000
_, err = tx.Exec(func() error {
r.writeShareSolo(tx, ms, ts, login, id, diff, shareDiffCalc, window, hostname)
tx.HIncrBy(r.formatKey("stats"), "roundShares", diff)
return nil
})
return false, err
}
func (r *RedisClient) GetNetworkDifficulty() (*big.Int, error) {
NetworkDifficultyDivShareDiff := big.NewInt(0)
m, err := r.GetNodeStates()
if err != nil {
return NetworkDifficultyDivShareDiff, err
}
for _, value := range m {
for legend, data := range value {
if legend == "difficulty" {
NetworkDifficultyDivShareDiff.SetString(join(data), 10)
return NetworkDifficultyDivShareDiff, nil
}
}
}
return NetworkDifficultyDivShareDiff, err
}
func (r *RedisClient) LogIP(login string, ip string) {
r.client.HSet(r.formatKey("settings", login), "ip_address", ip)
r.client.HSet(r.formatKey("settings", login), "status", "online")
r.client.HSet(r.formatKey("settings", login), "email_sent", "0")
ms := util.MakeTimestamp()
ts := ms / 1000
r.client.HSet(r.formatKey("settings", login), "ip_time", strconv.FormatInt(ts, 10))
}
func (r *RedisClient) WriteBlock(login, id string, params []string, diff, shareDiffCalc int64, roundDiff int64, height uint64, window time.Duration, hostname string) (bool, error) {
exist, err := r.checkPoWExist(height, params)
if err != nil {
return false, err
}
// Duplicate share, (nonce, powHash, mixDigest) pair exist
if exist {
return true, nil
}
tx := r.client.Multi()
defer tx.Close()
ms := util.MakeTimestamp()
ts := ms / 1000
var s string
cmds, err := tx.Exec(func() error {
r.writeShare(tx, ms, ts, login, id, diff, shareDiffCalc, window, hostname)
tx.HSet(r.formatKey("stats"), "lastBlockFound", strconv.FormatInt(ts, 10))
tx.HDel(r.formatKey("stats"), "roundShares")
tx.HSet(r.formatKey("miners", login), "roundShares", strconv.FormatInt(0, 10))
tx.ZIncrBy(r.formatKey("finders"), 1, login)
tx.HIncrBy(r.formatKey("miners", login), "blocksFound", 1)
tx.HGetAllMap(r.formatKey("shares", "roundCurrent"))
tx.Del(r.formatKey("shares", "roundCurrent"))
tx.LRange(r.formatKey("lastshares"), 0, r.pplns)
return nil
})
r.WriteBlocksFound(ms, ts, login, id, params[0], diff)
if err != nil {
return false, err
} else {
shares := cmds[len(cmds)-1].(*redis.StringSliceCmd).Val()
tx2 := r.client.Multi()
defer tx2.Close()
totalshares := make(map[string]int64)
for _, val := range shares {
totalshares[val] += 1
}
_, err := tx2.Exec(func() error {
for k, v := range totalshares {
tx2.HIncrBy(r.formatRound(int64(height), params[0]), k, v)
}
return nil
})
if err != nil {
return false, err
}
sharesMap, _ := cmds[len(cmds)-3].(*redis.StringStringMapCmd).Result()
totalShares := int64(0)
for _, v := range sharesMap {
n, _ := strconv.ParseInt(v, 10, 64)
totalShares += n
}
personalShares := int64(0)
personalShares = cmds[len(cmds)-14].(*redis.IntCmd).Val()
hashHex := strings.Join(params, ":")
s = join(hashHex, ts, roundDiff, totalShares, login, id, "pplns", shareDiffCalc, personalShares)
//log.Println("CANDIDATES s : ", s)
cmd := r.client.ZAdd(r.formatKey("blocks", "candidates"), redis.Z{Score: float64(height), Member: s})
return false, cmd.Err()
}
}
func (r *RedisClient) WriteBlockSolo(login, id string, params []string, diff, shareDiffCalc int64, roundDiff int64, height uint64, window time.Duration, hostname string) (bool, error) {
exist, err := r.checkPoWExist(height, params)
if err != nil {
return false, err
}
// Duplicate share, (nonce, powHash, mixDigest) pair exist
if exist {
return true, nil
}
tx := r.client.Multi()
defer tx.Close()
ms := util.MakeTimestamp()
ts := ms / 1000
var s string
cmds, err := tx.Exec(func() error {
r.writeShare(tx, ms, ts, login, id, diff, shareDiffCalc, window, hostname)
tx.HSet(r.formatKey("stats"), "lastBlockFound", strconv.FormatInt(ts, 10))
tx.HDel(r.formatKey("stats"), "roundShares")
tx.HSet(r.formatKey("miners", login), "roundShares", strconv.FormatInt(0, 10))
tx.ZIncrBy(r.formatKey("finders"), 1, login)
tx.HIncrBy(r.formatKey("miners", login), "blocksFound", 1)
tx.HGetAllMap(r.formatKey("shares", "roundCurrent"))
tx.Del(r.formatKey("shares", "roundCurrent"))
tx.LRange(r.formatKey("lastshares_solo"), 0, 0)
return nil
})
r.WriteBlocksFound(ms, ts, login, id, params[0], diff)
if err != nil {
return false, err
} else {
shares := cmds[len(cmds)-1].(*redis.StringSliceCmd).Val()
tx2 := r.client.Multi()
defer tx2.Close()
totalshares := make(map[string]int64)
for _, val := range shares {
totalshares[val] += 1
}
_, err := tx2.Exec(func() error {
for k, v := range totalshares {
tx2.HIncrBy(r.formatRound(int64(height), params[0]), k, v)
}
return nil
})
if err != nil {
return false, err
}
sharesMap, _ := cmds[len(cmds)-3].(*redis.StringStringMapCmd).Result()
totalShares := int64(0)
for _, v := range sharesMap {
n, _ := strconv.ParseInt(v, 10, 64)
totalShares += n
}
personalShares := int64(0)
personalShares = cmds[len(cmds)-14].(*redis.IntCmd).Val()
hashHex := strings.Join(params, ":")
s = join(hashHex, ts, roundDiff, totalShares, login, id, "solo", shareDiffCalc, personalShares)
//log.Println("CANDIDATES s : ", s)
cmd := r.client.ZAdd(r.formatKey("blocks", "candidates"), redis.Z{Score: float64(height), Member: s})
return false, cmd.Err()
}
}
// writeShare processes and stores miner shares in Redis
func (r *RedisClient) writeShare(tx *redis.Multi, ms, ts int64, login, id string, diff int64, shareDiffCalc int64, expire time.Duration, hostname string) {
// Calculate the number of seconds in the difference time
times := int(diff / 1000000000)
// Push the miner's name 'times' times into a Redis list
for i := 0; i < times; i++ {
tx.LPush(r.formatKey("lastshares"), login)
}
// Calculate the dynamic PPLNS value based on miner performance
dynamicPPLNS := r.calculateDynamicPPLNS(login)
// Trim the list to the dynamic PPLNS value
tx.LTrim(r.formatKey("lastshares"), 0, dynamicPPLNS)
// Increase the number of round shares for the miner
tx.HIncrBy(r.formatKey("miners", login), "roundShares", diff)
// Increase the current round shares for the miner
tx.HIncrBy(r.formatKey("shares", "roundCurrent"), login, diff)
// Add the hashrate value for the entire group
tx.ZAdd(r.formatKey("hashrate"), redis.Z{Score: float64(ts), Member: join(diff, login, id, ms, diff, hostname)})
// Add the hashrate value for the individual miner
tx.ZAdd(r.formatKey("hashrate", login), redis.Z{Score: float64(ts), Member: join(diff, id, ms, diff, hostname)})
// Set an expiration time for the miner's hashrate data
tx.Expire(r.formatKey("hashrate", login), expire)
// Set the value of the last share and its difficulty
tx.HSet(r.formatKey("miners", login), "lastShare", strconv.FormatInt(ts, 10))
tx.HSet(r.formatKey("miners", login), "lastShareDiff", strconv.FormatInt(shareDiffCalc, 10))
}
// calculateDynamicPPLNS calculates the dynamic PPLNS value based on miner performance
func (r *RedisClient) calculateDynamicPPLNS(login string) int64 {
// Number of shares of the miner in the last 10 minutes
sharesCount := r.getSharesCount(login, 10*60) // 10 minutes
// Using the base PPLNS value from the RedisClient structure
if sharesCount > r.pplns {
// Increase the PPLNS value if the miner has more shares than the base value
return r.pplns + (sharesCount / 100)
} else {
// Decrease the PPLNS value if the miner has fewer shares than the base value
return r.pplns - ((r.pplns - sharesCount) / 100)
}
}
// getSharesCount returns the number of shares of a miner within a specific period
func (r *RedisClient) getSharesCount(login string, duration int64) int64 {
now := time.Now().Unix()
past := now - duration
// Retrieve the number of shares from Redis
shares, err := r.client.ZCount(r.formatKey("shares", login), strconv.FormatInt(past, 10), strconv.FormatInt(now, 10)).Result()
if err != nil {
log.Println("Error retrieving shares:", err)
return 0
}
return shares
}
func (r *RedisClient) writeShareSolo(tx *redis.Multi, ms, ts int64, login, id string, diff int64, shareDiffCalc int64, expire time.Duration, hostname string) {
times := int(diff / 1000000000)
for i := 0; i < times; i++ {
tx.LPush(r.formatKey("lastshares_solo"), login)
}
tx.LTrim(r.formatKey("lastshares_solo"), 0, 0)
tx.HIncrBy(r.formatKey("miners", login), "roundShares", diff)
tx.HIncrBy(r.formatKey("shares", "roundCurrent"), login, diff)
// For aggregation of hashrate, to store value in hashrate key
tx.ZAdd(r.formatKey("hashrate"), redis.Z{Score: float64(ts), Member: join(diff, login, id, ms, diff, hostname)})
// For separate miner's workers hashrate, to store under hashrate table under login key
tx.ZAdd(r.formatKey("hashrate", login), redis.Z{Score: float64(ts), Member: join(diff, id, ms, diff, hostname)})
// Will delete hashrates for miners that gone
tx.Expire(r.formatKey("hashrate", login), expire)
tx.HSet(r.formatKey("miners", login), "lastShare", strconv.FormatInt(ts, 10))
tx.HSet(r.formatKey("miners", login), "lastShareDiff", strconv.FormatInt(shareDiffCalc, 10))
}
func (r *RedisClient) formatKey(args ...interface{}) string {
return join(r.prefix, join(args...))
}
func (r *RedisClient) formatRound(height int64, nonce string) string {
return r.formatKey("shares", "round"+strconv.FormatInt(height, 10), nonce)
}
func (r *RedisClient) formatRoundSolo(height int64, nonce string) string {
return r.formatKey("shares_solo", "round"+strconv.FormatInt(height, 10), nonce)
}
func join(args ...interface{}) string {
s := make([]string, len(args))
for i, v := range args {
switch v.(type) {
case string:
s[i] = v.(string)
case int64:
s[i] = strconv.FormatInt(v.(int64), 10)
case uint64:
s[i] = strconv.FormatUint(v.(uint64), 10)
case float64:
s[i] = strconv.FormatFloat(v.(float64), 'f', 0, 64)
case bool:
if v.(bool) {
s[i] = "1"
} else {
s[i] = "0"
}
case *big.Int:
n := v.(*big.Int)
if n != nil {
s[i] = n.String()
} else {
s[i] = "0"
}
case *big.Rat:
x := v.(*big.Rat)
if x != nil {
s[i] = x.FloatString(9)
} else {
s[i] = "0"
}
default:
panic("Invalid type specified for conversion")
}
}
return strings.Join(s, ":")
}
func (r *RedisClient) GetCandidates(maxHeight int64) ([]*BlockData, error) {
option := redis.ZRangeByScore{Min: "0", Max: strconv.FormatInt(maxHeight, 10)}
cmd := r.client.ZRangeByScoreWithScores(r.formatKey("blocks", "candidates"), option)
if cmd.Err() != nil {
return nil, cmd.Err()
}
blockData := convertCandidateResults(cmd)
return blockData, nil
}
func (r *RedisClient) GetImmatureBlocks(maxHeight int64) ([]*BlockData, error) {
option := redis.ZRangeByScore{Min: "0", Max: strconv.FormatInt(maxHeight, 10)}
cmd := r.client.ZRangeByScoreWithScores(r.formatKey("blocks", "immature"), option)
if cmd.Err() != nil {
return nil, cmd.Err()
}
blockData := convertBlockResults(cmd)
return blockData, nil
}
func (r *RedisClient) GetRewards(login string) ([]*RewardData, error) {
option := redis.ZRangeByScore{Min: "0", Max: strconv.FormatInt(10, 10)}
cmd := r.client.ZRangeByScoreWithScores(r.formatKey("rewards", login), option)
if cmd.Err() != nil {
return nil, cmd.Err()
}
return convertRewardResults(cmd), nil
}
func (r *RedisClient) GetRoundShares(height int64, nonce string) (map[string]int64, error) {
result := make(map[string]int64)
cmd := r.client.HGetAllMap(r.formatRound(height, nonce))
if cmd.Err() != nil {
return nil, cmd.Err()
}
sharesMap, _ := cmd.Result()
for login, v := range sharesMap {
n, _ := strconv.ParseInt(v, 10, 64)
result[login] = n
}
return result, nil
}
func (r *RedisClient) GetPayees() ([]string, error) {
payees := make(map[string]struct{})
var result []string
var c int64
for {
var keys []string
var err error
c, keys, err = r.client.Scan(c, r.formatKey("miners", "*"), 100).Result()
if err != nil {
return nil, err
}
for _, row := range keys {
login := strings.Split(row, ":")[2]
payees[login] = struct{}{}
}
if c == 0 {
break
}
}
for login := range payees {
result = append(result, login)
}
return result, nil
}
func (r *RedisClient) GetTotalShares() (int64, error) {
cmd := r.client.LLen(r.formatKey("lastshares"))
if cmd.Err() == redis.Nil {
return 0, nil
} else if cmd.Err() != nil {
return 0, cmd.Err()
}
return cmd.Val(), nil
}
func (r *RedisClient) GetBalance(login string) (int64, error) {
cmd := r.client.HGet(r.formatKey("miners", login), "balance")
if cmd.Err() == redis.Nil {
return 0, nil
} else if cmd.Err() != nil {
return 0, cmd.Err()
}
return cmd.Int64()
}
func (r *RedisClient) GetThreshold(login string) (int64, error) {
cmd := r.client.HGet(r.formatKey("settings", login), "payoutthreshold")
if cmd.Err() == redis.Nil {
return 500000000, nil
} else if cmd.Err() != nil {
log.Println("GetThreshold error :", cmd.Err())
return 500000000, cmd.Err()
}
return cmd.Int64()
}
func (r *RedisClient) SetThreshold(login string, threshold int64) (bool, error) {
cmd, err := r.client.HSet(r.formatKey("settings", login), "payoutthreshold", strconv.FormatInt(threshold, 10)).Result()
return cmd, err
}
func (r *RedisClient) LockPayouts(login string, amount int64) error {
key := r.formatKey("payments", "lock")
result := r.client.SetNX(key, join(login, amount), 0).Val()
if !result {
return fmt.Errorf("Unable to acquire lock '%s'", key)
}
return nil
}
func (r *RedisClient) UnlockPayouts() error {
key := r.formatKey("payments", "lock")
_, err := r.client.Del(key).Result()
return err
}
func (r *RedisClient) IsPayoutsLocked() (bool, error) {
_, err := r.client.Get(r.formatKey("payments", "lock")).Result()
if err == redis.Nil {
return false, nil
} else if err != nil {
return false, err
} else {
return true, nil
}
}
type PendingPayment struct {
Timestamp int64 `json:"timestamp"`
Amount int64 `json:"amount"`
Address string `json:"login"`
}
func (r *RedisClient) GetPendingPayments() []*PendingPayment {
raw := r.client.ZRevRangeWithScores(r.formatKey("payments", "pending"), 0, -1)
var result []*PendingPayment
for _, v := range raw.Val() {
// timestamp -> "address:amount"
payment := PendingPayment{}
payment.Timestamp = int64(v.Score)
fields := strings.Split(v.Member.(string), ":")
payment.Address = fields[0]
payment.Amount, _ = strconv.ParseInt(fields[1], 10, 64)
result = append(result, &payment)
}
return result
}
// Deduct miner's balance for payment
func (r *RedisClient) UpdateBalance(login string, amount int64) error {
tx := r.client.Multi()
defer tx.Close()
ts := util.MakeTimestamp() / 1000
_, err := tx.Exec(func() error {
tx.HIncrBy(r.formatKey("miners", login), "balance", amount*-1)
tx.HIncrBy(r.formatKey("miners", login), "pending", amount)
tx.HIncrBy(r.formatKey("finances"), "balance", amount*-1)
tx.HIncrBy(r.formatKey("finances"), "pending", amount)
tx.ZAdd(r.formatKey("payments", "pending"), redis.Z{Score: float64(ts), Member: join(login, amount)})
return nil
})
return err
}
func (r *RedisClient) RollbackBalance(login string, amount int64) error {
tx := r.client.Multi()
defer tx.Close()
_, err := tx.Exec(func() error {
tx.HIncrBy(r.formatKey("miners", login), "balance", amount)
tx.HIncrBy(r.formatKey("miners", login), "pending", amount*-1)
tx.HIncrBy(r.formatKey("finances"), "balance", amount)
tx.HIncrBy(r.formatKey("finances"), "pending", amount*-1)
tx.ZRem(r.formatKey("payments", "pending"), join(login, amount))
return nil
})
return err
}
func (r *RedisClient) WritePayment(login, txHash string, amount int64, txCharges int64) error {
tx := r.client.Multi()
defer tx.Close()
ts := util.MakeTimestamp() / 1000
_, err := tx.Exec(func() error {
tx.HIncrBy(r.formatKey("miners", login), "pending", amount*-1)
tx.HIncrBy(r.formatKey("miners", login), "paid", amount)
tx.HIncrBy(r.formatKey("finances"), "pending", amount*-1)
tx.HIncrBy(r.formatKey("finances"), "paid", amount)
tx.HIncrBy(r.formatKey("finances"), "txcharges", txCharges)
tx.ZAdd(r.formatKey("payments", "all"), redis.Z{Score: float64(ts), Member: join(txHash, login, amount, txCharges)})
tx.ZAdd(r.formatKey("payments", login), redis.Z{Score: float64(ts), Member: join(txHash, amount, txCharges)})
tx.ZRem(r.formatKey("payments", "pending"), join(login, amount))
tx.Del(r.formatKey("payments", "lock"))
return nil
})
return err
}
func (r *RedisClient) WriteReward(login string, amount int64, percent *big.Rat, immature bool, block *BlockData) error {
if amount <= 0 {
return nil
}
tx := r.client.Multi()
defer tx.Close()
addStr := join(amount, percent, immature, block.Hash, block.Height, block.Timestamp, block.Difficulty, block.PersonalShares)
remStr := join(amount, percent, !immature, block.Hash, block.Height, block.Timestamp, block.Difficulty, block.PersonalShares)
remscore := block.Timestamp - 3600*24*90 // Store the last 90 Days
_, err := tx.Exec(func() error {
tx.ZAdd(r.formatKey("rewards", login), redis.Z{Score: float64(block.Timestamp), Member: addStr})
tx.ZRem(r.formatKey("rewards", login), remStr)
tx.ZRemRangeByScore(r.formatKey("rewards", login), "-inf", "("+strconv.FormatInt(remscore, 10))
return nil
})
return err
}
func (r *RedisClient) WriteImmatureBlock(block *BlockData, roundRewards map[string]int64) error {
tx := r.client.Multi()
defer tx.Close()
_, err := tx.Exec(func() error {
r.writeImmatureBlock(tx, block)
total := int64(0)
for login, amount := range roundRewards {
total += amount
tx.HIncrBy(r.formatKey("miners", login), "immature", amount)
tx.HSetNX(r.formatKey("credits", "immature", block.Height, block.Hash), login, strconv.FormatInt(amount, 10))
}
tx.HIncrBy(r.formatKey("finances"), "immature", total)
return nil
})
return err
}
func (r *RedisClient) WriteMaturedBlock(block *BlockData, roundRewards map[string]int64) error {
creditKey := r.formatKey("credits", "immature", block.RoundHeight, block.Hash)
tx, err := r.client.Watch(creditKey)
// Must decrement immatures using existing log entry
immatureCredits := tx.HGetAllMap(creditKey)
if err != nil {
return err
}
defer tx.Close()
ts := util.MakeTimestamp() / 1000
value := join(block.Hash, ts, block.Reward)
_, err = tx.Exec(func() error {
r.writeMaturedBlock(tx, block)
tx.ZAdd(r.formatKey("credits", "all"), redis.Z{Score: float64(block.Height), Member: value})
// Decrement immature balances
totalImmature := int64(0)
for login, amountString := range immatureCredits.Val() {
amount, _ := strconv.ParseInt(amountString, 10, 64)
totalImmature += amount
tx.HIncrBy(r.formatKey("miners", login), "immature", amount*-1)
}
// Increment balances
total := int64(0)
for login, amount := range roundRewards {
total += amount
// NOTICE: Maybe expire round reward entry in 604800 (a week)?
tx.HIncrBy(r.formatKey("miners", login), "balance", amount)
if amount > 0 {
tx.HSetNX(r.formatKey("credits", block.Height, block.Hash), login, strconv.FormatInt(amount, 10))
}
}
tx.Del(creditKey)
tx.HIncrBy(r.formatKey("finances"), "balance", total)
tx.HIncrBy(r.formatKey("finances"), "immature", totalImmature*-1)
tx.HSet(r.formatKey("finances"), "lastCreditHeight", strconv.FormatInt(block.Height, 10))
tx.HSet(r.formatKey("finances"), "lastCreditHash", block.Hash)
tx.HIncrBy(r.formatKey("finances"), "totalMined", block.RewardInShannon())
return nil
})
return err
}
func (r *RedisClient) WriteOrphan(block *BlockData) error {
creditKey := r.formatKey("credits", "immature", block.RoundHeight, block.Hash)
tx, err := r.client.Watch(creditKey)
// Must decrement immatures using existing log entry
immatureCredits := tx.HGetAllMap(creditKey)
if err != nil {
return err
}
defer tx.Close()
_, err = tx.Exec(func() error {
r.writeMaturedBlock(tx, block)
// Decrement immature balances
totalImmature := int64(0)
for login, amountString := range immatureCredits.Val() {
amount, _ := strconv.ParseInt(amountString, 10, 64)
totalImmature += amount
tx.HIncrBy(r.formatKey("miners", login), "immature", amount*-1)
}
tx.Del(creditKey)
tx.HIncrBy(r.formatKey("finances"), "immature", totalImmature*-1)
return nil
})
return err
}
func (r *RedisClient) WritePendingOrphans(blocks []*BlockData) error {
tx := r.client.Multi()
defer tx.Close()
_, err := tx.Exec(func() error {
for _, block := range blocks {
r.writeImmatureBlock(tx, block)
}
return nil
})
return err
}
func (r *RedisClient) writeImmatureBlock(tx *redis.Multi, block *BlockData) {
if block.Height != block.RoundHeight {
tx.Rename(r.formatRound(block.RoundHeight, block.Nonce), r.formatRound(block.Height, block.Nonce))
}
tx.ZRem(r.formatKey("blocks", "candidates"), block.candidateKey)
tx.ZAdd(r.formatKey("blocks", "immature"), redis.Z{Score: float64(block.Height), Member: block.key()})
}
func (r *RedisClient) writeMaturedBlock(tx *redis.Multi, block *BlockData) {
tx.Del(r.formatRound(block.RoundHeight, block.Nonce))
tx.ZRem(r.formatKey("blocks", "immature"), block.immatureKey)
tx.ZAdd(r.formatKey("blocks", "matured"), redis.Z{Score: float64(block.Height), Member: block.key()})
}
func (r *RedisClient) IsMinerExists(login string) (bool, error) {
return r.client.Exists(r.formatKey("miners", login)).Result()
}
func (r *RedisClient) GetMinerStats(login string, maxPayments int64) (map[string]interface{}, error) {
stats := make(map[string]interface{})
tx := r.client.Multi()
defer tx.Close()
cmds, err := tx.Exec(func() error {
tx.HGetAllMap(r.formatKey("miners", login))
tx.ZRevRangeWithScores(r.formatKey("payments", login), 0, maxPayments-1)