-
Notifications
You must be signed in to change notification settings - Fork 0
/
methods.go
4223 lines (3761 loc) · 124 KB
/
methods.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) 2013-2016 The btcsuite developers
// Copyright (c) 2015-2020 The Hdfchain developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package jsonrpc
import (
"bytes"
"context"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"math/big"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/hdfchain/hdfwallet/errors"
"github.com/hdfchain/hdfwallet/p2p"
"github.com/hdfchain/hdfwallet/rpc/client/hdfd"
"github.com/hdfchain/hdfwallet/rpc/jsonrpc/types"
"github.com/hdfchain/hdfwallet/spv"
"github.com/hdfchain/hdfwallet/version"
"github.com/hdfchain/hdfwallet/wallet"
"github.com/hdfchain/hdfwallet/wallet/txauthor"
"github.com/hdfchain/hdfwallet/wallet/txrules"
"github.com/hdfchain/hdfwallet/wallet/udb"
"github.com/hdfchain/hdfd/blockchain/stake/v3"
blockchain "github.com/hdfchain/hdfd/blockchain/standalone"
"github.com/hdfchain/hdfd/chaincfg/chainhash"
"github.com/hdfchain/hdfd/chaincfg/v3"
"github.com/hdfchain/hdfd/dcrec"
"github.com/hdfchain/hdfd/dcrjson/v3"
"github.com/hdfchain/hdfd/dcrutil/v3"
"github.com/hdfchain/hdfd/hdkeychain/v3"
hdfdtypes "github.com/hdfchain/hdfd/rpc/jsonrpc/types/v2"
"github.com/hdfchain/hdfd/txscript/v3"
"github.com/hdfchain/hdfd/wire"
"golang.org/x/sync/errgroup"
)
// API version constants
const (
jsonrpcSemverString = "8.3.0"
jsonrpcSemverMajor = 8
jsonrpcSemverMinor = 3
jsonrpcSemverPatch = 0
)
// confirms returns the number of confirmations for a transaction in a block at
// height txHeight (or -1 for an unconfirmed tx) given the chain height
// curHeight.
func confirms(txHeight, curHeight int32) int32 {
switch {
case txHeight == -1, txHeight > curHeight:
return 0
default:
return curHeight - txHeight + 1
}
}
// the registered rpc handlers
var handlers = map[string]handler{
// Reference implementation wallet methods (implemented)
"abandontransaction": {fn: (*Server).abandonTransaction},
"accountaddressindex": {fn: (*Server).accountAddressIndex},
"accountsyncaddressindex": {fn: (*Server).accountSyncAddressIndex},
"addmultisigaddress": {fn: (*Server).addMultiSigAddress},
"addtransaction": {fn: (*Server).addTransaction},
"auditreuse": {fn: (*Server).auditReuse},
"consolidate": {fn: (*Server).consolidate},
"createmultisig": {fn: (*Server).createMultiSig},
"createrawtransaction": {fn: (*Server).createRawTransaction},
"createsignature": {fn: (*Server).createSignature},
"discoverusage": {fn: (*Server).discoverUsage},
"dumpprivkey": {fn: (*Server).dumpPrivKey},
"fundrawtransaction": {fn: (*Server).fundRawTransaction},
"generatevote": {fn: (*Server).generateVote},
"getaccount": {fn: (*Server).getAccount},
"getaccountaddress": {fn: (*Server).getAccountAddress},
"getaddressesbyaccount": {fn: (*Server).getAddressesByAccount},
"getbalance": {fn: (*Server).getBalance},
"getbestblockhash": {fn: (*Server).getBestBlockHash},
"getblockcount": {fn: (*Server).getBlockCount},
"getblockhash": {fn: (*Server).getBlockHash},
"getinfo": {fn: (*Server).getInfo},
"getmasterpubkey": {fn: (*Server).getMasterPubkey},
"getmultisigoutinfo": {fn: (*Server).getMultisigOutInfo},
"getnewaddress": {fn: (*Server).getNewAddress},
"getrawchangeaddress": {fn: (*Server).getRawChangeAddress},
"getreceivedbyaccount": {fn: (*Server).getReceivedByAccount},
"getreceivedbyaddress": {fn: (*Server).getReceivedByAddress},
"getstakeinfo": {fn: (*Server).getStakeInfo},
"gettickets": {fn: (*Server).getTickets},
"gettransaction": {fn: (*Server).getTransaction},
"getvotechoices": {fn: (*Server).getVoteChoices},
"getwalletfee": {fn: (*Server).getWalletFee},
"help": {fn: (*Server).help},
"importcfiltersv2": {fn: (*Server).importCFiltersV2},
"importprivkey": {fn: (*Server).importPrivKey},
"importscript": {fn: (*Server).importScript},
"importxpub": {fn: (*Server).importXpub},
"listaccounts": {fn: (*Server).listAccounts},
"listlockunspent": {fn: (*Server).listLockUnspent},
"listreceivedbyaccount": {fn: (*Server).listReceivedByAccount},
"listreceivedbyaddress": {fn: (*Server).listReceivedByAddress},
"listsinceblock": {fn: (*Server).listSinceBlock},
"listtransactions": {fn: (*Server).listTransactions},
"listunspent": {fn: (*Server).listUnspent},
"lockunspent": {fn: (*Server).lockUnspent},
"mixaccount": {fn: (*Server).mixAccount},
"mixoutput": {fn: (*Server).mixOutput},
"purchaseticket": {fn: (*Server).purchaseTicket},
"rescanwallet": {fn: (*Server).rescanWallet},
"revoketickets": {fn: (*Server).revokeTickets},
"sendfrom": {fn: (*Server).sendFrom},
"sendmany": {fn: (*Server).sendMany},
"sendtoaddress": {fn: (*Server).sendToAddress},
"sendtomultisig": {fn: (*Server).sendToMultiSig},
"getcoinjoinsbyacct": {fn: (*Server).getcoinjoinsbyacct},
"settxfee": {fn: (*Server).setTxFee},
"setvotechoice": {fn: (*Server).setVoteChoice},
"signmessage": {fn: (*Server).signMessage},
"signrawtransaction": {fn: (*Server).signRawTransaction},
"signrawtransactions": {fn: (*Server).signRawTransactions},
"stakepooluserinfo": {fn: (*Server).stakePoolUserInfo},
"sweepaccount": {fn: (*Server).sweepAccount},
"redeemmultisigout": {fn: (*Server).redeemMultiSigOut},
"redeemmultisigouts": {fn: (*Server).redeemMultiSigOuts},
"ticketinfo": {fn: (*Server).ticketInfo},
"ticketsforaddress": {fn: (*Server).ticketsForAddress},
"validateaddress": {fn: (*Server).validateAddress},
"validatepredcp0005cf": {fn: (*Server).validatePreDCP0005CF},
"verifymessage": {fn: (*Server).verifyMessage},
"version": {fn: (*Server).version},
"walletinfo": {fn: (*Server).walletInfo},
"walletlock": {fn: (*Server).walletLock},
"walletpassphrase": {fn: (*Server).walletPassphrase},
"walletpassphrasechange": {fn: (*Server).walletPassphraseChange},
// Extensions to the reference client JSON-RPC API
"getbestblock": {fn: (*Server).getBestBlock},
"createnewaccount": {fn: (*Server).createNewAccount},
"getpeerinfo": {fn: (*Server).getPeerInfo},
// This was an extension but the reference implementation added it as
// well, but with a different API (no account parameter). It's listed
// here because it hasn't been update to use the reference
// implemenation's API.
"getunconfirmedbalance": {fn: (*Server).getUnconfirmedBalance},
"listaddresstransactions": {fn: (*Server).listAddressTransactions},
"listalltransactions": {fn: (*Server).listAllTransactions},
"renameaccount": {fn: (*Server).renameAccount},
"walletislocked": {fn: (*Server).walletIsLocked},
// Reference implementation methods (still unimplemented)
"backupwallet": {fn: unimplemented, noHelp: true},
"getwalletinfo": {fn: unimplemented, noHelp: true},
"importwallet": {fn: unimplemented, noHelp: true},
"listaddressgroupings": {fn: unimplemented, noHelp: true},
// Reference methods which can't be implemented by hdfwallet due to
// design decision differences
"dumpwallet": {fn: unsupported, noHelp: true},
"encryptwallet": {fn: unsupported, noHelp: true},
"move": {fn: unsupported, noHelp: true},
"setaccount": {fn: unsupported, noHelp: true},
}
// unimplemented handles an unimplemented RPC request with the
// appropriate error.
func unimplemented(*Server, context.Context, interface{}) (interface{}, error) {
return nil, &dcrjson.RPCError{
Code: dcrjson.ErrRPCUnimplemented,
Message: "Method unimplemented",
}
}
// unsupported handles a standard bitcoind RPC request which is
// unsupported by hdfwallet due to design differences.
func unsupported(*Server, context.Context, interface{}) (interface{}, error) {
return nil, &dcrjson.RPCError{
Code: -1,
Message: "Request unsupported by hdfwallet",
}
}
// lazyHandler is a closure over a requestHandler or passthrough request with
// the RPC server's wallet and chain server variables as part of the closure
// context.
type lazyHandler func() (interface{}, *dcrjson.RPCError)
// lazyApplyHandler looks up the best request handler func for the method,
// returning a closure that will execute it with the (required) wallet and
// (optional) consensus RPC server. If no handlers are found and the
// chainClient is not nil, the returned handler performs RPC passthrough.
func lazyApplyHandler(s *Server, ctx context.Context, request *dcrjson.Request) lazyHandler {
handlerData, ok := handlers[request.Method]
if !ok {
return func() (interface{}, *dcrjson.RPCError) {
// Attempt RPC passthrough if possible
n, ok := s.walletLoader.NetworkBackend()
if !ok {
return nil, errRPCClientNotConnected
}
rpc, ok := n.(*hdfd.RPC)
if !ok {
return nil, rpcErrorf(dcrjson.ErrRPCClientNotConnected, "RPC passthrough requires hdfd RPC synchronization")
}
var resp json.RawMessage
var params = make([]interface{}, len(request.Params))
for i := range request.Params {
params[i] = request.Params[i]
}
err := rpc.Call(ctx, request.Method, &resp, params...)
if ctx.Err() != nil {
log.Warnf("Canceled RPC method %v invoked by %v: %v", request.Method, remoteAddr(ctx), err)
return nil, &dcrjson.RPCError{
Code: dcrjson.ErrRPCMisc,
Message: ctx.Err().Error(),
}
}
if err != nil {
return nil, convertError(err)
}
return resp, nil
}
}
return func() (interface{}, *dcrjson.RPCError) {
params, err := dcrjson.ParseParams(types.Method(request.Method), request.Params)
if err != nil {
return nil, dcrjson.ErrRPCInvalidRequest
}
defer func() {
if err := ctx.Err(); err != nil {
log.Warnf("Canceled RPC method %v invoked by %v: %v", request.Method, remoteAddr(ctx), err)
}
}()
resp, err := handlerData.fn(s, ctx, params)
if err != nil {
return nil, convertError(err)
}
return resp, nil
}
}
// makeResponse makes the JSON-RPC response struct for the result and error
// returned by a requestHandler. The returned response is not ready for
// marshaling and sending off to a client, but must be
func makeResponse(id, result interface{}, err error) dcrjson.Response {
idPtr := idPointer(id)
if err != nil {
return dcrjson.Response{
ID: idPtr,
Error: convertError(err),
}
}
resultBytes, err := json.Marshal(result)
if err != nil {
return dcrjson.Response{
ID: idPtr,
Error: &dcrjson.RPCError{
Code: dcrjson.ErrRPCInternal.Code,
Message: "Unexpected error marshalling result",
},
}
}
return dcrjson.Response{
ID: idPtr,
Result: json.RawMessage(resultBytes),
}
}
// abandonTransaction removes an unconfirmed transaction and all dependent
// transactions from the wallet.
func (s *Server) abandonTransaction(ctx context.Context, icmd interface{}) (interface{}, error) {
cmd := icmd.(*types.AbandonTransactionCmd)
w, ok := s.walletLoader.LoadedWallet()
if !ok {
return nil, errUnloadedWallet
}
hash, err := chainhash.NewHashFromStr(cmd.Hash)
if err != nil {
return nil, rpcError(dcrjson.ErrRPCDecodeHexString, err)
}
err = w.AbandonTransaction(ctx, hash)
return nil, err
}
// accountAddressIndex returns the next address index for the passed
// account and branch.
func (s *Server) accountAddressIndex(ctx context.Context, icmd interface{}) (interface{}, error) {
cmd := icmd.(*types.AccountAddressIndexCmd)
w, ok := s.walletLoader.LoadedWallet()
if !ok {
return nil, errUnloadedWallet
}
account, err := w.AccountNumber(ctx, cmd.Account)
if err != nil {
if errors.Is(err, errors.NotExist) {
return nil, errAccountNotFound
}
return nil, err
}
extChild, intChild, err := w.BIP0044BranchNextIndexes(ctx, account)
if err != nil {
return nil, err
}
switch uint32(cmd.Branch) {
case udb.ExternalBranch:
return extChild, nil
case udb.InternalBranch:
return intChild, nil
default:
return nil, rpcErrorf(dcrjson.ErrRPCInvalidParameter, "invalid branch %v", cmd.Branch)
}
}
// accountSyncAddressIndex synchronizes the address manager and local address
// pool for some account and branch to the passed index. If the current pool
// index is beyond the passed index, an error is returned. If the passed index
// is the same as the current pool index, nothing is returned. If the syncing
// is successful, nothing is returned.
func (s *Server) accountSyncAddressIndex(ctx context.Context, icmd interface{}) (interface{}, error) {
cmd := icmd.(*types.AccountSyncAddressIndexCmd)
w, ok := s.walletLoader.LoadedWallet()
if !ok {
return nil, errUnloadedWallet
}
account, err := w.AccountNumber(ctx, cmd.Account)
if err != nil {
if errors.Is(err, errors.NotExist) {
return nil, errAccountNotFound
}
return nil, err
}
branch := uint32(cmd.Branch)
index := uint32(cmd.Index)
if index >= hdkeychain.HardenedKeyStart {
return nil, rpcErrorf(dcrjson.ErrRPCInvalidParameter,
"child index %d exceeds the maximum child index for an account", index)
}
// Additional addresses need to be watched. Since addresses are derived
// based on the last used address, this RPC no longer changes the child
// indexes that new addresses are derived from.
return nil, w.SyncLastReturnedAddress(ctx, account, branch, index)
}
// walletPubKeys decodes each encoded key or address to a public key. If the
// address is P2PKH, the wallet is queried for the public key.
func walletPubKeys(ctx context.Context, w *wallet.Wallet, keys []string) ([]*dcrutil.AddressSecpPubKey, error) {
pubKeyAddrs := make([]*dcrutil.AddressSecpPubKey, len(keys))
for i, key := range keys {
addr, err := decodeAddress(key, w.ChainParams())
if err != nil {
return nil, err
}
switch addr := addr.(type) {
case *dcrutil.AddressSecpPubKey:
pubKeyAddrs[i] = addr
continue
}
a, err := w.KnownAddress(ctx, addr)
if err != nil {
if errors.Is(err, errors.NotExist) {
return nil, errAddressNotInWallet
}
return nil, err
}
var pubKey []byte
switch a := a.(type) {
case wallet.PubKeyHashAddress:
pubKey = a.PubKey()
default:
err = errors.New("address has no associated public key")
return nil, rpcError(dcrjson.ErrRPCInvalidAddressOrKey, err)
}
pubKeyAddr, err := dcrutil.NewAddressSecpPubKey(pubKey, w.ChainParams())
if err != nil {
return nil, err
}
pubKeyAddrs[i] = pubKeyAddr
}
return pubKeyAddrs, nil
}
// addMultiSigAddress handles an addmultisigaddress request by adding a
// multisig address to the given wallet.
func (s *Server) addMultiSigAddress(ctx context.Context, icmd interface{}) (interface{}, error) {
cmd := icmd.(*types.AddMultisigAddressCmd)
// If an account is specified, ensure that is the imported account.
if cmd.Account != nil && *cmd.Account != udb.ImportedAddrAccountName {
return nil, errNotImportedAccount
}
w, ok := s.walletLoader.LoadedWallet()
if !ok {
return nil, errUnloadedWallet
}
pubKeyAddrs, err := walletPubKeys(ctx, w, cmd.Keys)
if err != nil {
return nil, err
}
script, err := txscript.MultiSigScript(pubKeyAddrs, cmd.NRequired)
if err != nil {
return nil, err
}
err = w.ImportScript(ctx, script)
if err != nil && !errors.Is(err, errors.Exist) {
return nil, err
}
return dcrutil.NewAddressScriptHash(script, w.ChainParams())
}
func (s *Server) addTransaction(ctx context.Context, icmd interface{}) (interface{}, error) {
cmd := icmd.(*types.AddTransactionCmd)
w, ok := s.walletLoader.LoadedWallet()
if !ok {
return nil, errUnloadedWallet
}
blockHash, err := chainhash.NewHashFromStr(cmd.BlockHash)
if err != nil {
return nil, rpcError(dcrjson.ErrRPCDecodeHexString, err)
}
tx := new(wire.MsgTx)
err = tx.Deserialize(hex.NewDecoder(strings.NewReader(cmd.Transaction)))
if err != nil {
return nil, rpcError(dcrjson.ErrRPCDeserialization, err)
}
err = w.AddTransaction(ctx, tx, blockHash)
return nil, err
}
// auditReuse returns an object keying reused addresses to two or more outputs
// referencing them.
func (s *Server) auditReuse(ctx context.Context, icmd interface{}) (interface{}, error) {
cmd := icmd.(*types.AuditReuseCmd)
w, ok := s.walletLoader.LoadedWallet()
if !ok {
return nil, errUnloadedWallet
}
var since int32
if cmd.Since != nil {
since = *cmd.Since
}
reuse := make(map[string][]string)
inRange := make(map[string]struct{})
params := w.ChainParams()
err := w.GetTransactions(ctx, func(b *wallet.Block) (bool, error) {
for _, tx := range b.Transactions {
// Votes and revocations are skipped because they must
// only pay to addresses previously committed to by
// ticket purchases, and this "address reuse" is
// expected.
switch tx.Type {
case wallet.TransactionTypeVote, wallet.TransactionTypeRevocation:
continue
}
for _, out := range tx.MyOutputs {
addr := out.Address.String()
outpoints := reuse[addr]
outpoint := wire.OutPoint{Hash: *tx.Hash, Index: out.Index}
reuse[addr] = append(outpoints, outpoint.String())
if b.Header == nil || int32(b.Header.Height) >= since {
inRange[addr] = struct{}{}
}
}
if tx.Type != wallet.TransactionTypeTicketPurchase {
continue
}
ticket := new(wire.MsgTx)
err := ticket.Deserialize(bytes.NewReader(tx.Transaction))
if err != nil {
return false, err
}
for i := 1; i < len(ticket.TxOut); i += 2 { // iterate commitments
out := ticket.TxOut[i]
addr, err := stake.AddrFromSStxPkScrCommitment(out.PkScript, params)
if err != nil {
return false, err
}
have, err := w.HaveAddress(ctx, addr)
if err != nil {
return false, err
}
if !have {
continue
}
s := addr.String()
outpoints := reuse[s]
outpoint := wire.OutPoint{Hash: *tx.Hash, Index: uint32(i)}
reuse[s] = append(outpoints, outpoint.String())
if b.Header == nil || int32(b.Header.Height) >= since {
inRange[s] = struct{}{}
}
}
}
return false, nil
}, nil, nil)
if err != nil {
return nil, err
}
for s, outpoints := range reuse {
if len(outpoints) <= 1 {
delete(reuse, s)
continue
}
if _, ok := inRange[s]; !ok {
delete(reuse, s)
}
}
return reuse, nil
}
// consolidate handles a consolidate request by returning attempting to compress
// as many inputs as given and then returning the txHash and error.
func (s *Server) consolidate(ctx context.Context, icmd interface{}) (interface{}, error) {
cmd := icmd.(*types.ConsolidateCmd)
w, ok := s.walletLoader.LoadedWallet()
if !ok {
return nil, errUnloadedWallet
}
account := uint32(udb.DefaultAccountNum)
var err error
if cmd.Account != nil {
account, err = w.AccountNumber(ctx, *cmd.Account)
if err != nil {
if errors.Is(err, errors.NotExist) {
return nil, errAccountNotFound
}
return nil, err
}
}
// Set change address if specified.
var changeAddr dcrutil.Address
if cmd.Address != nil {
if *cmd.Address != "" {
addr, err := decodeAddress(*cmd.Address, w.ChainParams())
if err != nil {
return nil, err
}
changeAddr = addr
}
}
// TODO In the future this should take the optional account and
// only consolidate UTXOs found within that account.
txHash, err := w.Consolidate(ctx, cmd.Inputs, account, changeAddr)
if err != nil {
return nil, err
}
return txHash.String(), nil
}
// createMultiSig handles an createmultisig request by returning a
// multisig address for the given inputs.
func (s *Server) createMultiSig(ctx context.Context, icmd interface{}) (interface{}, error) {
cmd := icmd.(*types.CreateMultisigCmd)
w, ok := s.walletLoader.LoadedWallet()
if !ok {
return nil, errUnloadedWallet
}
pubKeyAddrs, err := walletPubKeys(ctx, w, cmd.Keys)
if err != nil {
return nil, err
}
script, err := txscript.MultiSigScript(pubKeyAddrs, cmd.NRequired)
if err != nil {
return nil, err
}
address, err := dcrutil.NewAddressScriptHash(script, w.ChainParams())
if err != nil {
return nil, err
}
return types.CreateMultiSigResult{
Address: address.Address(),
RedeemScript: hex.EncodeToString(script),
}, nil
}
// createRawTransaction handles createrawtransaction commands.
func (s *Server) createRawTransaction(ctx context.Context, icmd interface{}) (interface{}, error) {
cmd := icmd.(*hdfdtypes.CreateRawTransactionCmd)
// Validate expiry, if given.
if cmd.Expiry != nil && *cmd.Expiry < 0 {
return nil, rpcErrorf(dcrjson.ErrRPCInvalidParameter, "Expiry out of range")
}
// Validate the locktime, if given.
if cmd.LockTime != nil &&
(*cmd.LockTime < 0 ||
*cmd.LockTime > int64(wire.MaxTxInSequenceNum)) {
return nil, rpcErrorf(dcrjson.ErrRPCInvalidParameter, "Locktime out of range")
}
// Add all transaction inputs to a new transaction after performing
// some validity checks.
mtx := wire.NewMsgTx()
for _, input := range cmd.Inputs {
txHash, err := chainhash.NewHashFromStr(input.Txid)
if err != nil {
return nil, rpcError(dcrjson.ErrRPCInvalidParameter, err)
}
switch input.Tree {
case wire.TxTreeRegular, wire.TxTreeStake:
default:
return nil, rpcErrorf(dcrjson.ErrRPCInvalidParameter,
"Tx tree must be regular or stake")
}
amt, err := dcrutil.NewAmount(input.Amount)
if err != nil {
return nil, rpcError(dcrjson.ErrRPCInvalidParameter, err)
}
if amt < 0 {
return nil, rpcErrorf(dcrjson.ErrRPCInvalidParameter,
"Positive input amount is required")
}
prevOut := wire.NewOutPoint(txHash, input.Vout, input.Tree)
txIn := wire.NewTxIn(prevOut, int64(amt), nil)
if cmd.LockTime != nil && *cmd.LockTime != 0 {
txIn.Sequence = wire.MaxTxInSequenceNum - 1
}
mtx.AddTxIn(txIn)
}
// Add all transaction outputs to the transaction after performing
// some validity checks.
for encodedAddr, amount := range cmd.Amounts {
// Decode the provided address. This also ensures the network encoded
// with the address matches the network the server is currently on.
addr, err := dcrutil.DecodeAddress(encodedAddr, s.activeNet)
if err != nil {
return nil, rpcErrorf(dcrjson.ErrRPCInvalidAddressOrKey,
"Address %q: %v", encodedAddr, err)
}
// Ensure the address is one of the supported types.
switch addr.(type) {
case *dcrutil.AddressPubKeyHash:
case *dcrutil.AddressScriptHash:
default:
return nil, rpcErrorf(dcrjson.ErrRPCInvalidAddressOrKey,
"Invalid type: %T", addr)
}
// Create a new script which pays to the provided address.
pkScript, err := txscript.PayToAddrScript(addr)
if err != nil {
return nil, rpcErrorf(dcrjson.ErrRPCInternal.Code,
"Pay to address script: %v", err)
}
atomic, err := dcrutil.NewAmount(amount)
if err != nil {
return nil, rpcErrorf(dcrjson.ErrRPCInternal.Code,
"New amount: %v", err)
}
// Ensure amount is in the valid range for monetary amounts.
if atomic <= 0 || atomic > dcrutil.MaxAmount {
return nil, rpcErrorf(dcrjson.ErrRPCInvalidParameter,
"Amount outside valid range: %v", atomic)
}
txOut := wire.NewTxOut(int64(atomic), pkScript)
mtx.AddTxOut(txOut)
}
// Set the Locktime, if given.
if cmd.LockTime != nil {
mtx.LockTime = uint32(*cmd.LockTime)
}
// Set the Expiry, if given.
if cmd.Expiry != nil {
mtx.Expiry = uint32(*cmd.Expiry)
}
// Return the serialized and hex-encoded transaction.
sb := new(strings.Builder)
err := mtx.Serialize(hex.NewEncoder(sb))
if err != nil {
return nil, err
}
return sb.String(), nil
}
// createSignature creates a signature using the private key of a wallet
// address for a transaction input script. The serialized compressed public
// key of the address is also returned.
func (s *Server) createSignature(ctx context.Context, icmd interface{}) (interface{}, error) {
cmd := icmd.(*types.CreateSignatureCmd)
w, ok := s.walletLoader.LoadedWallet()
if !ok {
return nil, errUnloadedWallet
}
serializedTx, err := hex.DecodeString(cmd.SerializedTransaction)
if err != nil {
return nil, rpcError(dcrjson.ErrRPCDecodeHexString, err)
}
var tx wire.MsgTx
err = tx.Deserialize(bytes.NewReader(serializedTx))
if err != nil {
return nil, rpcError(dcrjson.ErrRPCDeserialization, err)
}
if cmd.InputIndex >= len(tx.TxIn) {
return nil, rpcErrorf(dcrjson.ErrRPCMisc,
"transaction input %d does not exist", cmd.InputIndex)
}
addr, err := decodeAddress(cmd.Address, w.ChainParams())
if err != nil {
return nil, err
}
hashType := txscript.SigHashType(cmd.HashType)
prevOutScript, err := hex.DecodeString(cmd.PreviousPkScript)
if err != nil {
return nil, rpcError(dcrjson.ErrRPCDecodeHexString, err)
}
sig, pubkey, err := w.CreateSignature(ctx, &tx, uint32(cmd.InputIndex),
addr, hashType, prevOutScript)
if err != nil {
return nil, err
}
return &types.CreateSignatureResult{
Signature: hex.EncodeToString(sig),
PublicKey: hex.EncodeToString(pubkey),
}, nil
}
func (s *Server) discoverUsage(ctx context.Context, icmd interface{}) (interface{}, error) {
cmd := icmd.(*types.DiscoverUsageCmd)
w, ok := s.walletLoader.LoadedWallet()
if !ok {
return nil, errUnloadedWallet
}
n, ok := s.walletLoader.NetworkBackend()
if !ok {
return nil, errNoNetwork
}
startBlock := w.ChainParams().GenesisHash
if cmd.StartBlock != nil {
h, err := chainhash.NewHashFromStr(*cmd.StartBlock)
if err != nil {
return nil, rpcErrorf(dcrjson.ErrRPCInvalidParameter, "startblock: %v", err)
}
startBlock = *h
}
discoverAccounts := cmd.DiscoverAccounts != nil && *cmd.DiscoverAccounts
gapLimit := w.GapLimit()
if cmd.GapLimit != nil {
gapLimit = *cmd.GapLimit
}
err := w.DiscoverActiveAddresses(ctx, n, &startBlock, discoverAccounts, gapLimit)
return nil, err
}
// dumpPrivKey handles a dumpprivkey request with the private key
// for a single address, or an appropriate error if the wallet
// is locked.
func (s *Server) dumpPrivKey(ctx context.Context, icmd interface{}) (interface{}, error) {
cmd := icmd.(*types.DumpPrivKeyCmd)
w, ok := s.walletLoader.LoadedWallet()
if !ok {
return nil, errUnloadedWallet
}
addr, err := decodeAddress(cmd.Address, w.ChainParams())
if err != nil {
return nil, err
}
key, err := w.DumpWIFPrivateKey(ctx, addr)
if err != nil {
if errors.Is(err, errors.Locked) {
return nil, errWalletUnlockNeeded
}
return nil, err
}
return key, nil
}
func (s *Server) fundRawTransaction(ctx context.Context, icmd interface{}) (interface{}, error) {
cmd := icmd.(*types.FundRawTransactionCmd)
w, ok := s.walletLoader.LoadedWallet()
if !ok {
return nil, errUnloadedWallet
}
var (
changeAddress string
feeRate = w.RelayFee()
confs = int32(1)
)
if cmd.Options != nil {
opts := cmd.Options
var err error
if opts.ChangeAddress != nil {
changeAddress = *opts.ChangeAddress
}
if opts.FeeRate != nil {
feeRate, err = dcrutil.NewAmount(*opts.FeeRate)
if err != nil {
return nil, err
}
}
if opts.ConfTarget != nil {
confs = *opts.ConfTarget
if confs < 0 {
return nil, errors.New("confs must be non-negative")
}
}
}
tx := new(wire.MsgTx)
err := tx.Deserialize(hex.NewDecoder(strings.NewReader(cmd.HexString)))
if err != nil {
return nil, err
}
// Existing inputs are problematic. Without information about
// how large the input scripts will be once signed, the wallet is
// unable to perform correct fee estimation. If fundrawtransaction
// is changed later to work on a PSDT structure that includes this
// information, this functionality may be enabled. For now, prevent
// the method from continuing.
if len(tx.TxIn) != 0 {
return nil, errors.New("transaction must not already have inputs")
}
accountNum, err := w.AccountNumber(ctx, cmd.FundAccount)
if err != nil {
return nil, err
}
// Because there are no other inputs, a new transaction can be created.
var changeSource txauthor.ChangeSource
if changeAddress != "" {
var err error
changeSource, err = makeScriptChangeSource(changeAddress, 0, w.ChainParams())
if err != nil {
return nil, err
}
}
atx, err := w.NewUnsignedTransaction(ctx, tx.TxOut, feeRate, accountNum, confs,
wallet.OutputSelectionAlgorithmDefault, changeSource, nil)
if err != nil {
return nil, err
}
// Include chosen inputs and change output (if any) in decoded
// transaction.
tx.TxIn = atx.Tx.TxIn
if atx.ChangeIndex >= 0 {
tx.TxOut = append(tx.TxOut, atx.Tx.TxOut[atx.ChangeIndex])
}
// Determine the absolute fee of the funded transaction
fee := atx.TotalInput
for i := range tx.TxOut {
fee -= dcrutil.Amount(tx.TxOut[i].Value)
}
b := new(strings.Builder)
b.Grow(2 * tx.SerializeSize())
err = tx.Serialize(hex.NewEncoder(b))
if err != nil {
return nil, err
}
res := &types.FundRawTransactionResult{
Hex: b.String(),
Fee: fee.ToCoin(),
}
return res, nil
}
// generateVote handles a generatevote request by constructing a signed
// vote and returning it.
func (s *Server) generateVote(ctx context.Context, icmd interface{}) (interface{}, error) {
cmd := icmd.(*types.GenerateVoteCmd)
w, ok := s.walletLoader.LoadedWallet()
if !ok {
return nil, errUnloadedWallet
}
blockHash, err := chainhash.NewHashFromStr(cmd.BlockHash)
if err != nil {
return nil, rpcError(dcrjson.ErrRPCDecodeHexString, err)
}
ticketHash, err := chainhash.NewHashFromStr(cmd.TicketHash)
if err != nil {
return nil, rpcError(dcrjson.ErrRPCDecodeHexString, err)
}
var voteBitsExt []byte
voteBitsExt, err = hex.DecodeString(cmd.VoteBitsExt)
if err != nil {
return nil, rpcError(dcrjson.ErrRPCDecodeHexString, err)
}
voteBits := stake.VoteBits{
Bits: cmd.VoteBits,
ExtendedBits: voteBitsExt,
}
ssgentx, err := w.GenerateVoteTx(ctx, blockHash, int32(cmd.Height), ticketHash,
voteBits)
if err != nil {
return nil, err
}
var b strings.Builder
b.Grow(2 * ssgentx.SerializeSize())
err = ssgentx.Serialize(hex.NewEncoder(&b))
if err != nil {
return nil, err
}
resp := &types.GenerateVoteResult{
Hex: b.String(),
}
return resp, nil
}
// getAddressesByAccount handles a getaddressesbyaccount request by returning
// all addresses for an account, or an error if the requested account does
// not exist.
func (s *Server) getAddressesByAccount(ctx context.Context, icmd interface{}) (interface{}, error) {
cmd := icmd.(*types.GetAddressesByAccountCmd)
w, ok := s.walletLoader.LoadedWallet()
if !ok {
return nil, errUnloadedWallet
}
if cmd.Account == "imported" {
addrs, err := w.ImportedAddresses(ctx, cmd.Account)
if err != nil {
return nil, err
}
return knownAddressMarshaler(addrs), nil
}
account, err := w.AccountNumber(ctx, cmd.Account)
if err != nil {
if errors.Is(err, errors.NotExist) {
return nil, errAccountNotFound
}
return nil, err
}
xpub, err := w.AccountXpub(ctx, account)
if err != nil {
return nil, err
}
extBranch, err := xpub.Child(0)
if err != nil {
return nil, err
}