-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.go
3533 lines (3100 loc) · 103 KB
/
server.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
// Copyright (c) 2015-2016 The btcsuite developers
// Copyright (c) 2016-2017 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
// Package rpcserver implements the RPC API and is used by the main package to
// start gRPC services.
//
// Full documentation of the API implemented by this package is maintained in a
// language-agnostic document:
//
// https://github.com/picfight/pfcwallet/blob/master/rpc/documentation/api.md
//
// Any API changes must be performed according to the steps listed here:
//
// https://github.com/picfight/pfcwallet/blob/master/rpc/documentation/serverchanges.md
package rpcserver
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"net"
"sync"
"sync/atomic"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/picfight/pfcd/addrmgr"
"github.com/picfight/pfcd/blockchain/stake"
"github.com/picfight/pfcd/chaincfg"
"github.com/picfight/pfcd/chaincfg/chainhash"
"github.com/picfight/pfcd/dcrec"
"github.com/picfight/pfcd/dcrutil"
"github.com/picfight/pfcd/hdkeychain"
"github.com/picfight/pfcd/rpcclient"
"github.com/picfight/pfcd/txscript"
"github.com/picfight/pfcd/wire"
"github.com/picfight/pfcwallet/chain"
"github.com/picfight/pfcwallet/errors"
"github.com/picfight/pfcwallet/internal/cfgutil"
h "github.com/picfight/pfcwallet/internal/helpers"
"github.com/picfight/pfcwallet/internal/zero"
"github.com/picfight/pfcwallet/loader"
"github.com/picfight/pfcwallet/netparams"
"github.com/picfight/pfcwallet/p2p"
pb "github.com/picfight/pfcwallet/rpc/walletrpc"
"github.com/picfight/pfcwallet/spv"
"github.com/picfight/pfcwallet/ticketbuyer"
tbv2 "github.com/picfight/pfcwallet/ticketbuyer/v2"
"github.com/picfight/pfcwallet/wallet"
"github.com/picfight/pfcwallet/wallet/txauthor"
"github.com/picfight/pfcwallet/wallet/txrules"
"github.com/picfight/pfcwallet/wallet/udb"
"github.com/picfight/pfcwallet/walletseed"
)
// Public API version constants
const (
semverString = "5.6.0"
semverMajor = 5
semverMinor = 6
semverPatch = 0
)
// translateError creates a new gRPC error with an appropiate error code for
// recognized errors.
//
// This function is by no means complete and should be expanded based on other
// known errors. Any RPC handler not returning a gRPC error (with status.Errorf)
// should return this result instead.
func translateError(err error) error {
code := errorCode(err)
return status.Errorf(code, "%s", err.Error())
}
func errorCode(err error) codes.Code {
var inner error
if err, ok := err.(*errors.Error); ok {
switch err.Kind {
case errors.Bug:
case errors.Invalid:
return codes.InvalidArgument
case errors.Permission:
return codes.PermissionDenied
case errors.IO:
case errors.Exist:
return codes.AlreadyExists
case errors.NotExist:
return codes.NotFound
case errors.Encoding:
case errors.Crypto:
return codes.DataLoss
case errors.Locked:
return codes.FailedPrecondition
case errors.Passphrase:
return codes.InvalidArgument
case errors.Seed:
return codes.InvalidArgument
case errors.WatchingOnly:
return codes.Unimplemented
case errors.InsufficientBalance:
return codes.ResourceExhausted
case errors.ScriptFailure:
case errors.Policy:
case errors.DoubleSpend:
case errors.Protocol:
case errors.NoPeers:
return codes.Unavailable
default:
inner = err.Err
for {
err, ok := inner.(*errors.Error)
if !ok {
break
}
inner = err.Err
}
}
}
switch inner {
case hdkeychain.ErrInvalidSeedLen:
return codes.InvalidArgument
}
return codes.Unknown
}
// decodeAddress decodes an address and verifies it is intended for the active
// network. This should be used preferred to direct usage of
// dcrutil.DecodeAddress, which does not perform the network check.
func decodeAddress(a string, params *chaincfg.Params) (dcrutil.Address, error) {
addr, err := dcrutil.DecodeAddress(a)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid address %v: %v", a, err)
}
if !addr.IsForNet(params) {
return nil, status.Errorf(codes.InvalidArgument,
"address %v is not intended for use on %v", a, params.Name)
}
return addr, nil
}
func decodeHashes(in [][]byte) ([]*chainhash.Hash, error) {
out := make([]*chainhash.Hash, len(in))
var err error
for i, h := range in {
out[i], err = chainhash.NewHash(h)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "hash (hex %x): %v", h, err)
}
}
return out, nil
}
// versionServer provides RPC clients with the ability to query the RPC server
// version.
type versionServer struct{}
// walletServer provides wallet services for RPC clients.
type walletServer struct {
ready uint32 // atomic
wallet *wallet.Wallet
}
// loaderServer provides RPC clients with the ability to load and close wallets,
// as well as establishing a RPC connection to a pfcd consensus server.
type loaderServer struct {
ready uint32 // atomic
loader *loader.Loader
activeNet *netparams.Params
rpcClient *chain.RPCClient
mu sync.Mutex
}
// seedServer provides RPC clients with the ability to generate secure random
// seeds encoded in both binary and human-readable formats, and decode any
// human-readable input back to binary.
type seedServer struct{}
// ticketbuyerServer provides RPC clients with the ability to start/stop the
// automatic ticket buyer service.
type ticketbuyerServer struct {
ready uint32 // atomic
loader *loader.Loader
ticketbuyerCfg *ticketbuyer.Config
}
// ticketbuyerServer provides RPC clients with the ability to start/stop the
// automatic ticket buyer service.
type ticketbuyerV2Server struct {
ready uint32 // atomic
loader *loader.Loader
}
type agendaServer struct {
ready uint32 // atomic
activeNet *chaincfg.Params
}
type votingServer struct {
ready uint32 // atomic
wallet *wallet.Wallet
}
// messageVerificationServer provides RPC clients with the ability to verify
// that a message was signed using the private key of a particular address.
type messageVerificationServer struct{}
type decodeMessageServer struct {
chainParams *chaincfg.Params
}
// Singleton implementations of each service. Not all services are immediately
// usable.
var (
versionService versionServer
walletService walletServer
loaderService loaderServer
seedService seedServer
ticketBuyerService ticketbuyerServer
ticketBuyerV2Service ticketbuyerV2Server
agendaService agendaServer
votingService votingServer
messageVerificationService messageVerificationServer
decodeMessageService decodeMessageServer
)
// RegisterServices registers implementations of each gRPC service and registers
// it with the server. Not all service are ready to be used after registration.
func RegisterServices(server *grpc.Server) {
pb.RegisterVersionServiceServer(server, &versionService)
pb.RegisterWalletServiceServer(server, &walletService)
pb.RegisterWalletLoaderServiceServer(server, &loaderService)
pb.RegisterSeedServiceServer(server, &seedService)
pb.RegisterTicketBuyerServiceServer(server, &ticketBuyerService)
pb.RegisterTicketBuyerV2ServiceServer(server, &ticketBuyerV2Service)
pb.RegisterAgendaServiceServer(server, &agendaService)
pb.RegisterVotingServiceServer(server, &votingService)
pb.RegisterMessageVerificationServiceServer(server, &messageVerificationService)
pb.RegisterDecodeMessageServiceServer(server, &decodeMessageService)
}
var serviceMap = map[string]interface{}{
"walletrpc.VersionService": &versionService,
"walletrpc.WalletService": &walletService,
"walletrpc.WalletLoaderService": &loaderService,
"walletrpc.SeedService": &seedService,
"walletrpc.TicketBuyerService": &ticketBuyerService,
"walletrpc.TicketBuyerV2Service": &ticketBuyerV2Service,
"walletrpc.AgendaService": &agendaService,
"walletrpc.VotingService": &votingService,
"walletrpc.MessageVerificationService": &messageVerificationService,
"walletrpc.DecodeMessageService": &decodeMessageService,
}
// ServiceReady returns nil when the service is ready and a gRPC error when not.
func ServiceReady(service string) error {
s, ok := serviceMap[service]
if !ok {
return status.Errorf(codes.Unimplemented, "service %s not found", service)
}
type readyChecker interface {
checkReady() bool
}
ready := true
r, ok := s.(readyChecker)
if ok {
ready = r.checkReady()
}
if !ready {
return status.Errorf(codes.FailedPrecondition, "service %v is not ready", service)
}
return nil
}
func (*versionServer) Version(ctx context.Context, req *pb.VersionRequest) (*pb.VersionResponse, error) {
return &pb.VersionResponse{
VersionString: semverString,
Major: semverMajor,
Minor: semverMinor,
Patch: semverPatch,
}, nil
}
// StartWalletService starts the WalletService.
func StartWalletService(server *grpc.Server, wallet *wallet.Wallet) {
walletService.wallet = wallet
if atomic.SwapUint32(&walletService.ready, 1) != 0 {
panic("service already started")
}
}
func (s *walletServer) checkReady() bool {
return atomic.LoadUint32(&s.ready) != 0
}
// requireNetworkBackend checks whether the wallet has been associated with the
// consensus server RPC client, returning a gRPC error when it is not.
func (s *walletServer) requireNetworkBackend() (wallet.NetworkBackend, error) {
n, err := s.wallet.NetworkBackend()
if err != nil {
return nil, status.Errorf(codes.FailedPrecondition,
"wallet is not associated with a consensus server RPC client")
}
return n, nil
}
func (s *walletServer) Ping(ctx context.Context, req *pb.PingRequest) (*pb.PingResponse, error) {
return &pb.PingResponse{}, nil
}
func (s *walletServer) Network(ctx context.Context, req *pb.NetworkRequest) (
*pb.NetworkResponse, error) {
return &pb.NetworkResponse{ActiveNetwork: uint32(s.wallet.ChainParams().Net)}, nil
}
func (s *walletServer) AccountNumber(ctx context.Context, req *pb.AccountNumberRequest) (
*pb.AccountNumberResponse, error) {
accountNum, err := s.wallet.AccountNumber(req.AccountName)
if err != nil {
return nil, translateError(err)
}
return &pb.AccountNumberResponse{AccountNumber: accountNum}, nil
}
func (s *walletServer) Accounts(ctx context.Context, req *pb.AccountsRequest) (*pb.AccountsResponse, error) {
resp, err := s.wallet.Accounts()
if err != nil {
return nil, translateError(err)
}
accounts := make([]*pb.AccountsResponse_Account, len(resp.Accounts))
for i := range resp.Accounts {
a := &resp.Accounts[i]
accounts[i] = &pb.AccountsResponse_Account{
AccountNumber: a.AccountNumber,
AccountName: a.AccountName,
TotalBalance: int64(a.TotalBalance),
ExternalKeyCount: a.LastUsedExternalIndex + 20, // Add gap limit
InternalKeyCount: a.LastUsedInternalIndex + 20,
ImportedKeyCount: a.ImportedKeyCount,
}
}
return &pb.AccountsResponse{
Accounts: accounts,
CurrentBlockHash: resp.CurrentBlockHash[:],
CurrentBlockHeight: resp.CurrentBlockHeight,
}, nil
}
func (s *walletServer) RenameAccount(ctx context.Context, req *pb.RenameAccountRequest) (
*pb.RenameAccountResponse, error) {
err := s.wallet.RenameAccount(req.AccountNumber, req.NewName)
if err != nil {
return nil, translateError(err)
}
return &pb.RenameAccountResponse{}, nil
}
func (s *walletServer) PublishUnminedTransactions(ctx context.Context, req *pb.PublishUnminedTransactionsRequest) (
*pb.PublishUnminedTransactionsResponse, error) {
n, err := s.requireNetworkBackend()
if err != nil {
return nil, err
}
err = s.wallet.PublishUnminedTransactions(ctx, n)
if err != nil {
return nil, translateError(err)
}
return &pb.PublishUnminedTransactionsResponse{}, nil
}
func (s *walletServer) Rescan(req *pb.RescanRequest, svr pb.WalletService_RescanServer) error {
n, err := s.requireNetworkBackend()
if err != nil {
return err
}
var blockID *wallet.BlockIdentifier
switch {
case req.BeginHash != nil && req.BeginHeight != 0:
return status.Errorf(codes.InvalidArgument, "begin hash and height must not be set together")
case req.BeginHeight < 0:
return status.Errorf(codes.InvalidArgument, "begin height must be non-negative")
case req.BeginHash != nil:
blockHash, err := chainhash.NewHash(req.BeginHash)
if err != nil {
return status.Errorf(codes.InvalidArgument, "block hash has invalid length")
}
blockID = wallet.NewBlockIdentifierFromHash(blockHash)
default:
blockID = wallet.NewBlockIdentifierFromHeight(req.BeginHeight)
}
b, err := s.wallet.BlockInfo(blockID)
if err != nil {
return translateError(err)
}
progress := make(chan wallet.RescanProgress, 1)
go s.wallet.RescanProgressFromHeight(svr.Context(), n, b.Height, progress)
for p := range progress {
if p.Err != nil {
return translateError(p.Err)
}
resp := &pb.RescanResponse{RescannedThrough: p.ScannedThrough}
err := svr.Send(resp)
if err != nil {
return translateError(err)
}
}
// finished or cancelled rescan without error
select {
case <-svr.Context().Done():
return status.Errorf(codes.Canceled, "rescan canceled")
default:
return nil
}
}
func (s *walletServer) NextAccount(ctx context.Context, req *pb.NextAccountRequest) (
*pb.NextAccountResponse, error) {
defer zero.Bytes(req.Passphrase)
if req.AccountName == "" {
return nil, status.Errorf(codes.InvalidArgument, "account name may not be empty")
}
lock := make(chan time.Time, 1)
defer func() {
lock <- time.Time{} // send matters, not the value
}()
err := s.wallet.Unlock(req.Passphrase, lock)
if err != nil {
return nil, translateError(err)
}
account, err := s.wallet.NextAccount(req.AccountName)
if err != nil {
return nil, translateError(err)
}
return &pb.NextAccountResponse{AccountNumber: account}, nil
}
func (s *walletServer) NextAddress(ctx context.Context, req *pb.NextAddressRequest) (
*pb.NextAddressResponse, error) {
var callOpts []wallet.NextAddressCallOption
switch req.GapPolicy {
case pb.NextAddressRequest_GAP_POLICY_UNSPECIFIED:
case pb.NextAddressRequest_GAP_POLICY_ERROR:
callOpts = append(callOpts, wallet.WithGapPolicyError())
case pb.NextAddressRequest_GAP_POLICY_IGNORE:
callOpts = append(callOpts, wallet.WithGapPolicyIgnore())
case pb.NextAddressRequest_GAP_POLICY_WRAP:
callOpts = append(callOpts, wallet.WithGapPolicyWrap())
default:
return nil, status.Errorf(codes.InvalidArgument, "gap_policy=%v", req.GapPolicy)
}
var (
addr dcrutil.Address
err error
)
switch req.Kind {
case pb.NextAddressRequest_BIP0044_EXTERNAL:
addr, err = s.wallet.NewExternalAddress(req.Account, callOpts...)
if err != nil {
return nil, translateError(err)
}
case pb.NextAddressRequest_BIP0044_INTERNAL:
addr, err = s.wallet.NewInternalAddress(req.Account, callOpts...)
if err != nil {
return nil, translateError(err)
}
default:
return nil, status.Errorf(codes.InvalidArgument, "kind=%v", req.Kind)
}
if err != nil {
return nil, translateError(err)
}
pubKey, err := s.wallet.PubKeyForAddress(addr)
if err != nil {
return nil, translateError(err)
}
pubKeyAddr, err := dcrutil.NewAddressSecpPubKey(pubKey.Serialize(), s.wallet.ChainParams())
if err != nil {
return nil, translateError(err)
}
return &pb.NextAddressResponse{
Address: addr.EncodeAddress(),
PublicKey: pubKeyAddr.String(),
}, nil
}
func (s *walletServer) ImportPrivateKey(ctx context.Context, req *pb.ImportPrivateKeyRequest) (
*pb.ImportPrivateKeyResponse, error) {
defer zero.Bytes(req.Passphrase)
wif, err := dcrutil.DecodeWIF(req.PrivateKeyWif)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument,
"Invalid WIF-encoded private key: %v", err)
}
lock := make(chan time.Time, 1)
defer func() {
lock <- time.Time{} // send matters, not the value
}()
err = s.wallet.Unlock(req.Passphrase, lock)
if err != nil {
return nil, translateError(err)
}
// At the moment, only the special-cased import account can be used to
// import keys.
if req.Account != udb.ImportedAddrAccount {
return nil, status.Errorf(codes.InvalidArgument,
"Only the imported account accepts private key imports")
}
if req.ScanFrom < 0 {
return nil, status.Errorf(codes.InvalidArgument,
"Attempted to scan from a negative block height")
}
if req.ScanFrom > 0 && req.Rescan {
return nil, status.Errorf(codes.InvalidArgument,
"Passed a rescan height without rescan set")
}
n, err := s.requireNetworkBackend()
if err != nil {
return nil, err
}
_, err = s.wallet.ImportPrivateKey(wif)
if err != nil {
return nil, translateError(err)
}
if req.Rescan {
go s.wallet.RescanFromHeight(context.Background(), n, req.ScanFrom)
}
return &pb.ImportPrivateKeyResponse{}, nil
}
func (s *walletServer) ImportScript(ctx context.Context,
req *pb.ImportScriptRequest) (*pb.ImportScriptResponse, error) {
defer zero.Bytes(req.Passphrase)
// TODO: Rather than assuming the "default" version, it must be a parameter
// to the request.
sc, addrs, requiredSigs, err := txscript.ExtractPkScriptAddrs(
txscript.DefaultScriptVersion, req.Script, s.wallet.ChainParams())
if err != nil && req.RequireRedeemable {
return nil, status.Errorf(codes.FailedPrecondition,
"The script is not redeemable by the wallet")
}
ownAddrs := 0
for _, a := range addrs {
haveAddr, err := s.wallet.HaveAddress(a)
if err != nil {
return nil, translateError(err)
}
if haveAddr {
ownAddrs++
}
}
redeemable := sc == txscript.MultiSigTy && ownAddrs >= requiredSigs
if !redeemable && req.RequireRedeemable {
return nil, status.Errorf(codes.FailedPrecondition,
"The script is not redeemable by the wallet")
}
if !s.wallet.Manager.WatchingOnly() {
lock := make(chan time.Time, 1)
defer func() {
lock <- time.Time{} // send matters, not the value
}()
err = s.wallet.Unlock(req.Passphrase, lock)
if err != nil {
return nil, translateError(err)
}
}
if req.ScanFrom < 0 {
return nil, status.Errorf(codes.InvalidArgument,
"Attempted to scan from a negative block height")
}
if req.ScanFrom > 0 && req.Rescan {
return nil, status.Errorf(codes.InvalidArgument,
"Passed a rescan height without rescan set")
}
n, err := s.requireNetworkBackend()
if err != nil {
return nil, err
}
err = s.wallet.ImportScript(req.Script)
if err != nil {
return nil, translateError(err)
}
if req.Rescan {
go s.wallet.RescanFromHeight(context.Background(), n, req.ScanFrom)
}
p2sh, err := dcrutil.NewAddressScriptHash(req.Script, s.wallet.ChainParams())
if err != nil {
return nil, translateError(err)
}
return &pb.ImportScriptResponse{P2ShAddress: p2sh.String(), Redeemable: redeemable}, nil
}
func (s *walletServer) Balance(ctx context.Context, req *pb.BalanceRequest) (
*pb.BalanceResponse, error) {
account := req.AccountNumber
reqConfs := req.RequiredConfirmations
bals, err := s.wallet.CalculateAccountBalance(account, reqConfs)
if err != nil {
return nil, translateError(err)
}
// TODO: Spendable currently includes multisig outputs that may not
// actually be spendable without additional keys.
resp := &pb.BalanceResponse{
Total: int64(bals.Total),
Spendable: int64(bals.Spendable),
ImmatureReward: int64(bals.ImmatureCoinbaseRewards),
ImmatureStakeGeneration: int64(bals.ImmatureStakeGeneration),
LockedByTickets: int64(bals.LockedByTickets),
VotingAuthority: int64(bals.VotingAuthority),
Unconfirmed: int64(bals.Unconfirmed),
}
return resp, nil
}
func (s *walletServer) TicketPrice(ctx context.Context, req *pb.TicketPriceRequest) (*pb.TicketPriceResponse, error) {
sdiff, err := s.wallet.NextStakeDifficulty()
if err == nil {
_, tipHeight := s.wallet.MainChainTip()
resp := &pb.TicketPriceResponse{
TicketPrice: int64(sdiff),
Height: tipHeight,
}
return resp, nil
}
n, err := s.requireNetworkBackend()
if err != nil {
return nil, err
}
chainClient, err := chain.RPCClientFromBackend(n)
if err != nil {
return nil, translateError(err)
}
ticketPrice, err := n.StakeDifficulty(ctx)
if err != nil {
return nil, translateError(err)
}
_, blockHeight, err := chainClient.GetBestBlock()
if err != nil {
return nil, translateError(err)
}
return &pb.TicketPriceResponse{
TicketPrice: int64(ticketPrice),
Height: int32(blockHeight),
}, nil
}
func (s *walletServer) StakeInfo(ctx context.Context, req *pb.StakeInfoRequest) (*pb.StakeInfoResponse, error) {
var chainClient *rpcclient.Client
if n, err := s.wallet.NetworkBackend(); err == nil {
client, err := chain.RPCClientFromBackend(n)
if err == nil {
chainClient = client
}
}
var si *wallet.StakeInfoData
var err error
if chainClient != nil {
si, err = s.wallet.StakeInfoPrecise(chainClient)
} else {
si, err = s.wallet.StakeInfo()
}
if err != nil {
return nil, translateError(err)
}
return &pb.StakeInfoResponse{
PoolSize: si.PoolSize,
AllMempoolTix: si.AllMempoolTix,
OwnMempoolTix: si.OwnMempoolTix,
Immature: si.Immature,
Live: si.Live,
Voted: si.Voted,
Missed: si.Missed,
Revoked: si.Revoked,
Expired: si.Expired,
TotalSubsidy: int64(si.TotalSubsidy),
Unspent: si.Unspent,
}, nil
}
// scriptChangeSource is a ChangeSource which is used to
// receive all correlated previous input value.
type scriptChangeSource struct {
version uint16
script []byte
}
func (src *scriptChangeSource) Script() ([]byte, uint16, error) {
return src.script, src.version, nil
}
func (src *scriptChangeSource) ScriptSize() int {
return len(src.script)
}
func makeScriptChangeSource(address string, version uint16) (*scriptChangeSource, error) {
destinationAddress, err := dcrutil.DecodeAddress(address)
if err != nil {
return nil, err
}
script, err := txscript.PayToAddrScript(destinationAddress)
if err != nil {
return nil, err
}
source := &scriptChangeSource{
version: version,
script: script,
}
return source, nil
}
func (s *walletServer) SweepAccount(ctx context.Context, req *pb.SweepAccountRequest) (*pb.SweepAccountResponse, error) {
feePerKb := s.wallet.RelayFee()
// Use provided fee per Kb if specified.
if req.FeePerKb < 0 {
return nil, status.Errorf(codes.InvalidArgument, "%s",
"fee per kb argument cannot be negative")
}
if req.FeePerKb > 0 {
var err error
feePerKb, err = dcrutil.NewAmount(req.FeePerKb)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "%v", err)
}
}
account, err := s.wallet.AccountNumber(req.SourceAccount)
if err != nil {
return nil, translateError(err)
}
changeSource, err := makeScriptChangeSource(req.DestinationAddress,
txscript.DefaultScriptVersion)
if err != nil {
return nil, translateError(err)
}
tx, err := s.wallet.NewUnsignedTransaction(nil, feePerKb, account,
int32(req.RequiredConfirmations), wallet.OutputSelectionAlgorithmAll,
changeSource)
if err != nil {
return nil, translateError(err)
}
var txBuf bytes.Buffer
txBuf.Grow(tx.Tx.SerializeSize())
err = tx.Tx.Serialize(&txBuf)
if err != nil {
return nil, translateError(err)
}
res := &pb.SweepAccountResponse{
UnsignedTransaction: txBuf.Bytes(),
TotalPreviousOutputAmount: int64(tx.TotalInput),
TotalOutputAmount: int64(h.SumOutputValues(tx.Tx.TxOut)),
EstimatedSignedSize: uint32(tx.EstimatedSignedSerializeSize),
}
return res, nil
}
func (s *walletServer) BlockInfo(ctx context.Context, req *pb.BlockInfoRequest) (*pb.BlockInfoResponse, error) {
var blockID *wallet.BlockIdentifier
switch {
case req.BlockHash != nil && req.BlockHeight != 0:
return nil, status.Errorf(codes.InvalidArgument, "block hash and height must not be set together")
case req.BlockHash != nil:
blockHash, err := chainhash.NewHash(req.BlockHash)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "block hash has invalid length")
}
blockID = wallet.NewBlockIdentifierFromHash(blockHash)
default:
blockID = wallet.NewBlockIdentifierFromHeight(req.BlockHeight)
}
b, err := s.wallet.BlockInfo(blockID)
if err != nil {
return nil, translateError(err)
}
header := new(wire.BlockHeader)
err = header.Deserialize(bytes.NewReader(b.Header[:]))
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to deserialize saved block header: %v", err)
}
return &pb.BlockInfoResponse{
BlockHash: b.Hash[:],
BlockHeight: b.Height,
Confirmations: b.Confirmations,
Timestamp: b.Timestamp,
BlockHeader: b.Header[:],
StakeInvalidated: b.StakeInvalidated,
ApprovesParent: header.VoteBits&dcrutil.BlockValid != 0,
}, nil
}
func (s *walletServer) UnspentOutputs(req *pb.UnspentOutputsRequest, svr pb.WalletService_UnspentOutputsServer) error {
policy := wallet.OutputSelectionPolicy{
Account: req.Account,
RequiredConfirmations: req.RequiredConfirmations,
}
inputDetail, err := s.wallet.SelectInputs(dcrutil.Amount(req.TargetAmount), policy)
// Do not return errors to caller when there was insufficient spendable
// outputs available for the target amount.
if err != nil && !errors.Is(errors.InsufficientBalance, err) {
return translateError(err)
}
var sum int64
for i, input := range inputDetail.Inputs {
select {
case <-svr.Context().Done():
return status.Errorf(codes.Canceled, "unspentoutputs cancelled")
default:
outputInfo, err := s.wallet.OutputInfo(&input.PreviousOutPoint)
if err != nil {
return translateError(err)
}
unspentOutput := &pb.UnspentOutputResponse{
TransactionHash: input.PreviousOutPoint.Hash[:],
OutputIndex: input.PreviousOutPoint.Index,
Tree: int32(input.PreviousOutPoint.Tree),
Amount: int64(outputInfo.Amount),
PkScript: inputDetail.Scripts[i],
ReceiveTime: outputInfo.Received.Unix(),
FromCoinbase: outputInfo.FromCoinbase,
}
sum += unspentOutput.Amount
unspentOutput.AmountSum = sum
err = svr.Send(unspentOutput)
if err != nil {
return translateError(err)
}
}
}
return nil
}
func (s *walletServer) FundTransaction(ctx context.Context, req *pb.FundTransactionRequest) (
*pb.FundTransactionResponse, error) {
policy := wallet.OutputSelectionPolicy{
Account: req.Account,
RequiredConfirmations: req.RequiredConfirmations,
}
inputDetail, err := s.wallet.SelectInputs(dcrutil.Amount(req.TargetAmount), policy)
// Do not return errors to caller when there was insufficient spendable
// outputs available for the target amount.
if err != nil && !errors.Is(errors.InsufficientBalance, err) {
return nil, translateError(err)
}
selectedOutputs := make([]*pb.FundTransactionResponse_PreviousOutput, len(inputDetail.Inputs))
for i, input := range inputDetail.Inputs {
outputInfo, err := s.wallet.OutputInfo(&input.PreviousOutPoint)
if err != nil {
return nil, translateError(err)
}
selectedOutputs[i] = &pb.FundTransactionResponse_PreviousOutput{
TransactionHash: input.PreviousOutPoint.Hash[:],
OutputIndex: input.PreviousOutPoint.Index,
Tree: int32(input.PreviousOutPoint.Tree),
Amount: int64(outputInfo.Amount),
PkScript: inputDetail.Scripts[i],
ReceiveTime: outputInfo.Received.Unix(),
FromCoinbase: outputInfo.FromCoinbase,
}
}
var changeScript []byte
if req.IncludeChangeScript && inputDetail.Amount > dcrutil.Amount(req.TargetAmount) {
changeAddr, err := s.wallet.NewChangeAddress(req.Account)
if err != nil {
return nil, translateError(err)
}
changeScript, err = txscript.PayToAddrScript(changeAddr)
if err != nil {
return nil, translateError(err)
}
}
return &pb.FundTransactionResponse{
SelectedOutputs: selectedOutputs,
TotalAmount: int64(inputDetail.Amount),
ChangePkScript: changeScript,
}, nil
}
func decodeDestination(dest *pb.ConstructTransactionRequest_OutputDestination,
chainParams *chaincfg.Params) (pkScript []byte, version uint16, err error) {
switch {
case dest == nil:
fallthrough
default:
return nil, 0, status.Errorf(codes.InvalidArgument, "unknown or missing output destination")
case dest.Address != "":
addr, err := decodeAddress(dest.Address, chainParams)
if err != nil {
return nil, 0, err
}
pkScript, err = txscript.PayToAddrScript(addr)
if err != nil {
return nil, 0, translateError(err)
}
version = txscript.DefaultScriptVersion
return pkScript, version, nil
case dest.Script != nil:
if dest.ScriptVersion > uint32(^uint16(0)) {
return nil, 0, status.Errorf(codes.InvalidArgument, "script_version overflows uint16")
}
return dest.Script, uint16(dest.ScriptVersion), nil
}
}
type txChangeSource struct {
version uint16
script []byte
}
func (src *txChangeSource) Script() ([]byte, uint16, error) {
return src.script, src.version, nil
}
func (src *txChangeSource) ScriptSize() int {
return len(src.script)
}
func makeTxChangeSource(destination *pb.ConstructTransactionRequest_OutputDestination,
chainParams *chaincfg.Params) (*txChangeSource, error) {
script, version, err := decodeDestination(destination, chainParams)
if err != nil {
return nil, err
}
changeSource := &txChangeSource{
script: script,
version: version,
}
return changeSource, nil
}