forked from decred/dcrstakepool
/
dcrclient.go
1440 lines (1287 loc) · 39.4 KB
/
dcrclient.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
// dcrclient.go
package controllers
import (
"encoding/hex"
"fmt"
"io/ioutil"
"sync"
"sync/atomic"
"time"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/dcrjson"
"github.com/decred/dcrrpcclient"
"github.com/decred/dcrstakepool/models"
"github.com/decred/dcrutil"
"github.com/decred/dcrwallet/wallet/udb"
)
// functionName
type functionName int
const (
validateAddressFn functionName = iota
createMultisigFn
importScriptFn
ticketsForAddressFn
getTxOutFn
getStakeInfoFn
connectedFn
stakePoolUserInfoFn
getBestBlockFn
)
var (
// cacheTimerStakeInfo is the duration of time after which to
// access the wallet and update the stake information instead
// of returning cached stake information.
cacheTimerStakeInfo = 5 * time.Minute
// cacheTimerGetTickets is the duration of time after which to
// access the wallet and update the ticket list for an address
// instead of returning cached ticket information.
cacheTimerGetTickets = 20 * time.Second
// defaultAccountName is the account name for the default wallet
// account as a string.
defaultAccountName = "default"
)
// validateAddressResponse
type validateAddressResponse struct {
addrInfo *dcrjson.ValidateAddressWalletResult
err error
}
// validateAddressMsg
type validateAddressMsg struct {
address dcrutil.Address
reply chan validateAddressResponse
}
// createMultisigResponse
type createMultisigResponse struct {
multisigInfo *dcrjson.CreateMultiSigResult
err error
}
// createMultisigMsg
type createMultisigMsg struct {
required int
addresses []dcrutil.Address
reply chan createMultisigResponse
}
// importScriptResponse
type importScriptResponse struct {
err error
}
// importScriptMsg
type importScriptMsg struct {
height int
script []byte
reply chan importScriptResponse
}
// ticketsForAddressResponse
type ticketsForAddressResponse struct {
tickets *dcrjson.TicketsForAddressResult
err error
}
// ticketsForAddressMsg
type ticketsForAddressMsg struct {
address dcrutil.Address
reply chan ticketsForAddressResponse
}
// getTxOutResponse
type getTxOutResponse struct {
txOut *dcrjson.GetTxOutResult
err error
}
// getTxOutMsg
type getTxOutMsg struct {
hash *chainhash.Hash
idx uint32
reply chan getTxOutResponse
}
// getStakeInfoResponse
type getStakeInfoResponse struct {
stakeInfo *dcrjson.GetStakeInfoResult
err error
}
// getStakeInfoMsg
type getStakeInfoMsg struct {
reply chan getStakeInfoResponse
}
// connectedResponse
type connectedResponse struct {
walletInfo []*dcrjson.WalletInfoResult
err error
}
// connectedMsg
type connectedMsg struct {
reply chan connectedResponse
}
// stakePoolUserInfoResponse
type stakePoolUserInfoResponse struct {
userInfo *dcrjson.StakePoolUserInfoResult
err error
}
// stakePoolUserInfoMsg
type stakePoolUserInfoMsg struct {
userAddr dcrutil.Address
reply chan stakePoolUserInfoResponse
takeFirstResponse bool
}
// getBestBlockResponse
type getBestBlockResponse struct {
bestBlockHash *chainhash.Hash
bestBlockHeight int64
err error
}
// getBestBlockMsg
type getBestBlockMsg struct {
reply chan getBestBlockResponse
}
// connectionError is an error relating to the connection,
// so that connection failures can be handled without
// crashing the server.
type connectionError error
// walletRPCHandler
func (w *walletSvrManager) walletRPCHandler() {
out:
for {
select {
case m := <-w.msgChan:
switch msg := m.(type) {
case validateAddressMsg:
resp := w.executeInSequence(validateAddressFn, msg)
respTyped := resp.(*validateAddressResponse)
msg.reply <- *respTyped
case createMultisigMsg:
resp := w.executeInSequence(createMultisigFn, msg)
respTyped := resp.(*createMultisigResponse)
msg.reply <- *respTyped
case importScriptMsg:
resp := w.executeInSequence(importScriptFn, msg)
respTyped := resp.(*importScriptResponse)
msg.reply <- *respTyped
case ticketsForAddressMsg:
resp := w.executeInSequence(ticketsForAddressFn, msg)
respTyped := resp.(*ticketsForAddressResponse)
msg.reply <- *respTyped
case getTxOutMsg:
resp := w.executeInSequence(getTxOutFn, msg)
respTyped := resp.(*getTxOutResponse)
msg.reply <- *respTyped
case getStakeInfoMsg:
resp := w.executeInSequence(getStakeInfoFn, msg)
respTyped := resp.(*getStakeInfoResponse)
msg.reply <- *respTyped
case connectedMsg:
resp := w.executeInSequence(connectedFn, msg)
respTyped := resp.(*connectedResponse)
msg.reply <- *respTyped
case stakePoolUserInfoMsg:
resp := w.executeInSequence(stakePoolUserInfoFn, msg)
respTyped := resp.(*stakePoolUserInfoResponse)
msg.reply <- *respTyped
case getBestBlockMsg:
resp := w.executeInSequence(getBestBlockFn, msg)
respTyped := resp.(*getBestBlockResponse)
msg.reply <- *respTyped
default:
log.Infof("Invalid message type in wallet RPC "+
"handler: %T", msg)
}
case <-w.quit:
break out
}
}
w.wg.Done()
log.Infof("Wallet RPC handler done")
}
// executeInSequence is the mainhandler of all the incoming client functions.
func (w *walletSvrManager) executeInSequence(fn functionName, msg interface{}) interface{} {
switch fn {
case validateAddressFn:
vam := msg.(validateAddressMsg)
resp := new(validateAddressResponse)
vawrs := make([]*dcrjson.ValidateAddressWalletResult, w.serversLen)
connectCount := 0
for i, s := range w.servers {
if w.servers[i] == nil {
continue
}
vawr, err := s.ValidateAddress(vam.address)
if err != nil && (err != dcrrpcclient.ErrClientDisconnect &&
err != dcrrpcclient.ErrClientShutdown) {
log.Infof("validateAddressFn failure on server %v: %v", i, err)
resp.err = err
return resp
} else if err != nil && (err == dcrrpcclient.ErrClientDisconnect ||
err == dcrrpcclient.ErrClientShutdown) {
vawrs[i] = nil
continue
}
connectCount++
vawrs[i] = vawr
}
if connectCount < w.minServers {
log.Errorf("Unable to check any servers for validateAddressFn")
resp.err = fmt.Errorf("not processing command; %v servers avail is below min of %v", connectCount, w.minServers)
return resp
}
for i := 0; i < w.serversLen; i++ {
if i == w.serversLen-1 {
break
}
if vawrs[i] == nil || vawrs[i+1] == nil {
continue
}
if vawrs[i].PubKey != vawrs[i+1].PubKey {
log.Infof("validateAddressFn nonequiv failure on servers "+
"%v, %v (%v != %v)", i, i+1, vawrs[i].PubKey, vawrs[i+1].PubKey)
resp.err = fmt.Errorf("non equivalent pubkey returned")
return resp
}
}
for i := range vawrs {
if vawrs[i] != nil {
resp.addrInfo = vawrs[i]
break
}
}
return resp
case createMultisigFn:
cmsm := msg.(createMultisigMsg)
resp := new(createMultisigResponse)
cmsrs := make([]*dcrjson.CreateMultiSigResult, w.serversLen)
connectCount := 0
for i, s := range w.servers {
if w.servers[i] == nil {
continue
}
cmsr, err := s.CreateMultisig(cmsm.required, cmsm.addresses)
if err != nil && (err != dcrrpcclient.ErrClientDisconnect &&
err != dcrrpcclient.ErrClientShutdown) {
log.Infof("createMultisigFn failure on server %v: %v", i, err)
resp.err = err
return resp
} else if err != nil && (err == dcrrpcclient.ErrClientDisconnect ||
err == dcrrpcclient.ErrClientShutdown) {
cmsrs[i] = nil
continue
}
connectCount++
cmsrs[i] = cmsr
}
if connectCount < w.minServers {
log.Errorf("Unable to check any servers for createMultisigFn")
resp.err = fmt.Errorf("not processing command; %v servers avail is below min of %v", connectCount, w.minServers)
return resp
}
for i := 0; i < w.serversLen; i++ {
if i == w.serversLen-1 {
break
}
if cmsrs[i] == nil || cmsrs[i+1] == nil {
continue
}
if cmsrs[i].RedeemScript != cmsrs[i+1].RedeemScript {
log.Infof("createMultisigFn nonequiv failure on servers "+
"%v, %v (%v != %v)", i, i+1, cmsrs[i].RedeemScript, cmsrs[i+1].RedeemScript)
resp.err = fmt.Errorf("non equivalent redeem script returned")
return resp
}
}
for i := range cmsrs {
if cmsrs[i] != nil {
resp.multisigInfo = cmsrs[i]
break
}
}
return resp
case importScriptFn:
ism := msg.(importScriptMsg)
resp := new(importScriptResponse)
isErrors := make([]error, w.serversLen)
for i, s := range w.servers {
if w.servers[i] == nil {
continue
}
err := s.ImportScriptRescanFrom(ism.script, true, ism.height)
isErrors[i] = err
}
for i := 0; i < w.serversLen; i++ {
if i == w.serversLen-1 {
break
}
notIsNil1 := isErrors[i] != nil
notIsNil2 := isErrors[i+1] != nil
if notIsNil1 != notIsNil2 {
log.Infof("importScriptFn nonequiv failure 1 on servers %v, %v",
i, i+1)
resp.err = fmt.Errorf("non equivalent error returned 1")
return resp
}
if notIsNil1 && notIsNil2 {
if isErrors[i].Error() != isErrors[i+1].Error() {
log.Infof("importScriptFn nonequiv failure 2 on "+
"servers %v, %v", i, i+1)
resp.err = fmt.Errorf("non equivalent error returned 2")
return resp
}
}
}
resp.err = isErrors[0]
return resp
case ticketsForAddressFn:
tfam := msg.(ticketsForAddressMsg)
resp := new(ticketsForAddressResponse)
tfars := make([]*dcrjson.TicketsForAddressResult, w.serversLen)
connectCount := 0
for i, s := range w.servers {
if w.servers[i] == nil {
continue
}
// Returns all tickets - even unconfirmed/mempool - when wallet is
// queried
tfar, err := s.TicketsForAddress(tfam.address)
if err != nil && (err != dcrrpcclient.ErrClientDisconnect &&
err != dcrrpcclient.ErrClientShutdown) {
log.Infof("ticketsForAddressFn failure on server %v: %v", i, err)
resp.err = err
return resp
} else if err != nil && (err == dcrrpcclient.ErrClientDisconnect ||
err == dcrrpcclient.ErrClientShutdown) {
tfars[i] = nil
continue
}
connectCount++
tfars[i] = tfar
}
if connectCount < w.minServers {
log.Errorf("Unable to check any servers for stakepooluserinfo")
resp.err = fmt.Errorf("not processing command; %v servers avail is below min of %v", connectCount, w.minServers)
return resp
}
for i := range tfars {
if tfars[i] != nil {
resp.tickets = tfars[i]
break
}
}
return resp
case getTxOutFn:
gtom := msg.(getTxOutMsg)
resp := new(getTxOutResponse)
gtors := make([]*dcrjson.GetTxOutResult, w.serversLen)
connectCount := 0
for i, s := range w.servers {
if w.servers[i] == nil {
continue
}
gtor, err := s.GetTxOut(gtom.hash, gtom.idx, true)
if err != nil && (err != dcrrpcclient.ErrClientDisconnect &&
err != dcrrpcclient.ErrClientShutdown) {
log.Infof("getTxOutFn failure on server %v: %v", i, err)
resp.err = err
return resp
} else if err != nil && (err == dcrrpcclient.ErrClientDisconnect ||
err == dcrrpcclient.ErrClientShutdown) {
gtors[i] = nil
continue
}
connectCount++
gtors[i] = gtor
}
if connectCount < w.minServers {
log.Errorf("Unable to check any servers for getTxOutFn")
resp.err = fmt.Errorf("not processing command; %v servers avail is below min of %v", connectCount, w.minServers)
return resp
}
for i := 0; i < w.serversLen; i++ {
if i == w.serversLen-1 {
break
}
if gtors[i] == nil || gtors[i+1] == nil {
continue
}
if gtors[i].ScriptPubKey.Hex != gtors[i+1].ScriptPubKey.Hex {
log.Infof("getTxOutFn nonequiv failure on servers "+
"%v, %v", i, i+1)
resp.err = fmt.Errorf("non equivalent ScriptPubKey returned")
return resp
}
}
for i := range gtors {
if gtors[i] != nil {
resp.txOut = gtors[i]
break
}
}
return resp
case getStakeInfoFn:
resp := new(getStakeInfoResponse)
gsirs := make([]*dcrjson.GetStakeInfoResult, w.serversLen)
connectCount := 0
for i, s := range w.servers {
if w.servers[i] == nil {
continue
}
gsir, err := s.GetStakeInfo()
if err != nil && (err != dcrrpcclient.ErrClientDisconnect &&
err != dcrrpcclient.ErrClientShutdown) {
log.Infof("getStakeInfoFn failure on server %v: %v", i, err)
resp.err = err
return resp
} else if err != nil && (err == dcrrpcclient.ErrClientDisconnect ||
err == dcrrpcclient.ErrClientShutdown) {
gsirs[i] = nil
continue
}
connectCount++
gsirs[i] = gsir
}
if connectCount < w.minServers {
log.Errorf("Unable to check any servers for getStakeInfoFn")
resp.err = fmt.Errorf("not processing command; %v servers avail is below min of %v", connectCount, w.minServers)
return resp
}
for i := 0; i < w.serversLen; i++ {
if i == w.serversLen-1 {
break
}
if gsirs[i] == nil || gsirs[i+1] == nil {
continue
}
if gsirs[i].Live != gsirs[i+1].Live {
log.Infof("getStakeInfoFn nonequiv failure on servers "+
"%v, %v", i, i+1)
resp.err = fmt.Errorf("non equivalent Live returned")
return resp
}
}
for i := range gsirs {
if gsirs[i] != nil {
resp.stakeInfo = gsirs[i]
break
}
}
return resp
// connectedFn actually requests walletinfo from the wallet and makes
// sure the daemon is connected and the wallet is unlocked.
case connectedFn:
resp := new(connectedResponse)
resp.err = nil
wirs := make([]*dcrjson.WalletInfoResult, w.serversLen)
resp.walletInfo = wirs
connectCount := 0
for i, s := range w.servers {
if w.servers[i] == nil {
continue
}
wir, err := s.WalletInfo()
if err != nil && (err != dcrrpcclient.ErrClientDisconnect &&
err != dcrrpcclient.ErrClientShutdown) {
log.Infof("connectedFn failure on server %v: %v", i, err)
resp.err = err
return resp
} else if err != nil && (err == dcrrpcclient.ErrClientDisconnect ||
err == dcrrpcclient.ErrClientShutdown) {
wirs[i] = nil
continue
}
connectCount++
wirs[i] = wir
}
if connectCount < w.minServers {
log.Errorf("Unable to check any servers for walletinfo")
resp.err = fmt.Errorf("not processing command; %v servers avail is below min of %v", connectCount, w.minServers)
return resp
}
for i := 0; i < w.serversLen; i++ {
if wirs[i] == nil {
continue
}
// Check to make sure we're connected to the daemon.
// If we aren't, send a failure.
if !wirs[i].DaemonConnected {
log.Infof("daemon connectivity failure on svr %v", i)
return fmt.Errorf("wallet server %v not connected to daemon", i)
}
// Check to make sure the wallet is unlocked.
if !wirs[i].Unlocked {
log.Infof("wallet svr %v not unlocked", i)
return fmt.Errorf("wallet server %v locked", i)
}
}
// TODO add infrastructure to decide if a certain number of
// wallets up/down is acceptable in the eyes of the admin.
// For example, allow for RPC calls to wallet if 2/3 are up,
// but err out and disallow if only 1/3 etc
return resp
case stakePoolUserInfoFn:
spuim := msg.(stakePoolUserInfoMsg)
resp := new(stakePoolUserInfoResponse)
// Taking first response, continuing on error
if spuim.takeFirstResponse {
for i, s := range w.servers {
spuir, err := s.StakePoolUserInfo(spuim.userAddr)
if err != nil {
log.Infof("stakePoolUserInfoFn failure on server %v: %v", i, err)
resp.err = err
continue
}
resp.err = nil
resp.userInfo = spuir
return resp
}
log.Warnf("All wallet servers failed to respond for StakePoolUserInfo.")
return resp
}
// Getting each wallet's response, checking for "syncness"
spuirs := make([]*dcrjson.StakePoolUserInfoResult, w.serversLen)
// use connectCount to increment total number of successful responses
// if we have > 0 then we proceed as though nothing is wrong for the user
connectCount := 0
for i, s := range w.servers {
if w.servers[i] == nil {
spuirs[i] = nil
continue
}
spuir, err := s.StakePoolUserInfo(spuim.userAddr)
if err != nil && (err != dcrrpcclient.ErrClientDisconnect &&
err != dcrrpcclient.ErrClientShutdown) {
log.Infof("stakePoolUserInfoFn failure on server %v: %v", i, err)
resp.err = err
return resp
} else if err != nil && (err == dcrrpcclient.ErrClientDisconnect ||
err == dcrrpcclient.ErrClientShutdown) {
spuirs[i] = nil
continue
}
connectCount++
spuirs[i] = spuir
}
if connectCount < w.minServers {
log.Errorf("Unable to check any servers for stakepooluserinfo")
resp.err = fmt.Errorf("not processing command; %v servers avail is below min of %v", connectCount, w.minServers)
return resp
}
if !w.checkForSyncness(spuirs) {
log.Infof("StakePoolUserInfo across wallets are not synced. Attempting to sync now")
w.syncTickets(spuirs)
}
for i := range spuirs {
if spuirs[i] != nil {
resp.userInfo = spuirs[i]
break
}
}
return resp
case getBestBlockFn:
resp := new(getBestBlockResponse)
for i, s := range w.servers {
if w.servers[i] == nil {
continue
}
hash, height, err := s.GetBestBlock()
if err != nil && (err != dcrrpcclient.ErrClientDisconnect &&
err != dcrrpcclient.ErrClientShutdown) {
log.Infof("getBestBlockFn failure on server %v: %v", i, err)
resp.err = err
return resp
} else if err != nil && (err == dcrrpcclient.ErrClientDisconnect ||
err == dcrrpcclient.ErrClientShutdown) {
continue
}
resp.bestBlockHeight = height
resp.bestBlockHash = hash
return resp
}
log.Errorf("Unable to check any servers for getBestBlockFn")
resp.err = fmt.Errorf("unable to get best block")
return resp
}
return nil
}
// ping pings all the servers and makes sure they're online. This should be
// performed before doing a write.
func (w *walletSvrManager) connected() ([]*dcrjson.WalletInfoResult, error) {
reply := make(chan connectedResponse)
w.msgChan <- connectedMsg{
reply: reply,
}
response := <-reply
return response.walletInfo, response.err
}
// syncTickets is called when checkForSyncness has returned false and the wallets
// PoolTickets need to be synced due to manual addtickets, or a status is off.
// If a ticket is seen to be valid in 1 wallet and invalid in another, we use
// addticket rpc command to add that ticket to the invalid wallet.
func (w *walletSvrManager) syncTickets(spuirs []*dcrjson.StakePoolUserInfoResult) error {
for i := 0; i < len(spuirs); i++ {
if w.servers[i] == nil {
continue
}
for j := 0; j < len(spuirs); j++ {
if w.servers[j] == nil {
continue
}
if i == j {
continue
}
for _, validTicket := range spuirs[i].Tickets {
for _, invalidTicket := range spuirs[j].InvalidTickets {
if validTicket.Ticket == invalidTicket {
hash, err := chainhash.NewHashFromStr(validTicket.Ticket)
if err != nil {
return err
}
tx, err := w.fetchTransaction(hash)
if err != nil {
return err
}
log.Infof("adding formally invalid ticket %v to %v", hash, i)
err = w.servers[j].AddTicket(tx)
if err != nil {
return err
}
}
}
}
}
}
return nil
}
// checkForSyncness is a helper function to iterate through results
// of StakePoolUserInfo requests from all the wallets and ensure
// that each share the others PoolTickets and have the same
// valid/invalid lists. If any thing is deemed off then syncTickets
// call is made.
func (w *walletSvrManager) checkForSyncness(spuirs []*dcrjson.StakePoolUserInfoResult) bool {
for i := 0; i < len(spuirs); i++ {
if spuirs[i] == nil {
continue
}
for k := 0; k < len(spuirs); k++ {
if spuirs[k] == nil {
continue
}
if &spuirs[i] == &spuirs[k] {
continue
}
if len(spuirs[i].Tickets) != len(spuirs[k].Tickets) {
log.Infof("valid tickets len don't match! server %v has %v "+
"server %v has %v", i, len(spuirs[i].Tickets), k,
len(spuirs[k].Tickets))
return false
}
if len(spuirs[i].InvalidTickets) != len(spuirs[k].InvalidTickets) {
log.Infof("invalid tickets len don't match! server %v has %v "+
"server %v has %v", i, len(spuirs[i].Tickets), k,
len(spuirs[k].Tickets))
return false
}
/* TODO
// for now we are going to just consider the situation where the
// lengths of invalid/valid tickets differ. When we have
// better infrastructure in stakepool wallets to update pool
// ticket status we can dig deeper into the scenarios and
// how best to resolve them.
for y := range spuirs[i].Tickets {
found := false
for z := range spuirs[k].Tickets {
if spuirs[i].Tickets[y] == spuirs[k].Tickets[z] {
found = true
break
}
}
if !found {
log.Infof("ticket not found! %v %v", i, spuirs[i].Tickets[y])
return false
}
}
for y := range spuirs[i].InvalidTickets {
found := false
for z := range spuirs[k].InvalidTickets {
if spuirs[i].InvalidTickets[y] == spuirs[k].InvalidTickets[z] {
found = true
break
}
}
if !found {
log.Infof("invalid ticket not found! %v %v", i, spuirs[i].InvalidTickets[y])
return false
}
}
*/
}
}
return true
}
// ValidateAddress
//
// This should return equivalent results from all wallet RPCs. If this
// encounters a failure, it should be considered fatal.
func (w *walletSvrManager) ValidateAddress(addr dcrutil.Address) (*dcrjson.ValidateAddressWalletResult, error) {
// Assert that all servers are online.
_, err := w.connected()
if err != nil {
return nil, connectionError(err)
}
reply := make(chan validateAddressResponse)
w.msgChan <- validateAddressMsg{
address: addr,
reply: reply,
}
response := <-reply
return response.addrInfo, response.err
}
// CreateMultisig
//
// This should return equivalent results from all wallet RPCs. If this
// encounters a failure, it should be considered fatal.
func (w *walletSvrManager) CreateMultisig(nreq int, addrs []dcrutil.Address) (*dcrjson.CreateMultiSigResult, error) {
// Assert that all servers are online.
_, err := w.connected()
if err != nil {
return nil, connectionError(err)
}
reply := make(chan createMultisigResponse)
w.msgChan <- createMultisigMsg{
required: nreq,
addresses: addrs,
reply: reply,
}
response := <-reply
return response.multisigInfo, response.err
}
// ImportScript
//
// This should return equivalent results from all wallet RPCs. If this
// encounters a failure, it should be considered fatal.
func (w *walletSvrManager) ImportScript(script []byte, height int) error {
// Assert that all servers are online.
_, err := w.connected()
if err != nil {
return connectionError(err)
}
reply := make(chan importScriptResponse)
w.msgChan <- importScriptMsg{
height: height,
script: script,
reply: reply,
}
response := <-reply
return response.err
}
// TicketsForAddress
//
// This can race depending on what wallet is currently processing, so failures
// from this function should NOT cause fatal errors on the web server like the
// other RPC client calls.
func (w *walletSvrManager) TicketsForAddress(address dcrutil.Address) (*dcrjson.TicketsForAddressResult, error) {
w.cachedGetTicketsMutex.Lock()
defer w.cachedGetTicketsMutex.Unlock()
// See if we already have a cached copy of this information.
// If it isn't too old, return that instead.
cachedResp, ok := w.cachedGetTicketsMap[address.EncodeAddress()]
if ok {
if time.Since(cachedResp.timer) < cacheTimerGetTickets {
return cachedResp.res, nil
}
}
reply := make(chan ticketsForAddressResponse)
w.msgChan <- ticketsForAddressMsg{
address: address,
reply: reply,
}
response := <-reply
// If there was no error, cache the response now.
if response.err != nil {
w.cachedGetTicketsMap[address.EncodeAddress()] =
NewGetTicketsCacheData(response.tickets)
}
return response.tickets, response.err
}
// GetTxOut gets a txOut status given a hash and an output index. It returns
// nothing if the output is spent, and a standard response if it is unspent.
//
// This can race depending on what wallet is currently processing, so failures
// from this function should NOT cause fatal errors on the web server like the
// other RPC client calls.
func (w *walletSvrManager) GetTxOut(hash *chainhash.Hash, idx uint32) (*dcrjson.GetTxOutResult, error) {
reply := make(chan getTxOutResponse)
w.msgChan <- getTxOutMsg{
hash: hash,
idx: idx,
reply: reply,
}
response := <-reply
return response.txOut, response.err
}
// StakePoolUserInfo gets the stake pool user information for a given user.
//
// This can race depending on what wallet is currently processing, so failures
// from this function should NOT cause fatal errors on the web server like the
// other RPC client calls.
func (w *walletSvrManager) StakePoolUserInfo(userAddr dcrutil.Address, takeFirstResponse bool) (*dcrjson.StakePoolUserInfoResult, error) {
reply := make(chan stakePoolUserInfoResponse)
w.msgChan <- stakePoolUserInfoMsg{
userAddr: userAddr,
reply: reply,
takeFirstResponse: takeFirstResponse,
}
response := <-reply
return response.userInfo, response.err
}
// GetBestBlock gets the current best block according the first wallet asked.
func (w *walletSvrManager) GetBestBlock() (*chainhash.Hash, int64, error) {
reply := make(chan getBestBlockResponse)
w.msgChan <- getBestBlockMsg{
reply: reply,
}
response := <-reply
return response.bestBlockHash, response.bestBlockHeight, response.err
}
// getStakeInfo returns the cached current stake statistics about the wallet if
// it has been less than five minutes. If it has been longer than five minutes,
// a new request for stake information is piped through the RPC client handler
// and then cached for future reuse.
//
// This can race depending on what wallet is currently processing, so failures
// from this function should NOT cause fatal errors on the web server like the
// other RPC client calls.
func (w *walletSvrManager) getStakeInfo() (*dcrjson.GetStakeInfoResult, error) {
// Less than five minutes has elapsed since the last call. Return
// the previously cached stake information.
if time.Since(w.cachedStakeInfoTimer) < cacheTimerStakeInfo {
return w.cachedStakeInfo, nil
}
// Five minutes or more has passed since the last call, so request new
// stake information.
reply := make(chan getStakeInfoResponse)
w.msgChan <- getStakeInfoMsg{
reply: reply,
}
response := <-reply
// If there was an error, return the error and do not reset
// the timer.
if response.err != nil {
return nil, response.err
}
// Cache the response for future use and reset the timer.
w.cachedStakeInfo = response.stakeInfo
w.cachedStakeInfoTimer = time.Now()
return response.stakeInfo, nil
}
// GetStakeInfo is the concurrency safe, exported version of getStakeInfo.
func (w *walletSvrManager) GetStakeInfo() (*dcrjson.GetStakeInfoResult, error) {
w.cachedStakeInfoMutex.Lock()
defer w.cachedStakeInfoMutex.Unlock()
return w.getStakeInfo()
}
// getTicketsCacheData is a TicketsForAddressResult that also contains a time
// at which TicketsForAddress was last called. The results should only update.
type getTicketsCacheData struct {
res *dcrjson.TicketsForAddressResult
timer time.Time
}
// NewGetTicketsCacheData is a contructor for getTicketsCacheData that sets the
// last get time to now.
func NewGetTicketsCacheData(tfar *dcrjson.TicketsForAddressResult) *getTicketsCacheData {
return &getTicketsCacheData{tfar, time.Now()}
}
// walletSvrManager provides a concurrency safe RPC call manager for handling
// all incoming wallet server requests.
type walletSvrManager struct {
servers []*dcrrpcclient.Client
serversLen int
walletHosts []string
walletCerts []string
walletUsers []string
walletPasswords []string
walletsLock sync.Mutex
// cachedStakeInfo is cached information about the stake pool wallet.
// This is required because of the time it takes to compute the
// stake information. The included timer is used so that new stake
// information is only queried for if 5 minutes or more has passed.
// The mutex is used to allow concurrent access to the stake
// information if less than five minutes has passed.
cachedStakeInfo *dcrjson.GetStakeInfoResult
cachedStakeInfoTimer time.Time