forked from gcash/bchwallet
/
methods.go
1958 lines (1734 loc) · 61.1 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-2017 The btcsuite developers
// Copyright (c) 2016 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package legacyrpc
import (
"bytes"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"sync"
"time"
"github.com/dcrlabs/bchwallet/chain"
"github.com/dcrlabs/bchwallet/waddrmgr"
"github.com/dcrlabs/bchwallet/wallet"
"github.com/dcrlabs/bchwallet/wallet/txrules"
"github.com/dcrlabs/bchwallet/wtxmgr"
"github.com/gcash/bchd/bchec"
"github.com/gcash/bchd/btcjson"
"github.com/gcash/bchd/chaincfg"
"github.com/gcash/bchd/chaincfg/chainhash"
"github.com/gcash/bchd/rpcclient"
"github.com/gcash/bchd/txscript"
"github.com/gcash/bchd/wire"
"github.com/gcash/bchutil"
)
// confirmed checks whether a transaction at height txHeight has met minconf
// confirmations for a blockchain at height curHeight.
func confirmed(minconf, txHeight, curHeight int32) bool {
return confirms(txHeight, curHeight) >= minconf
}
// 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
}
}
// requestHandler is a handler function to handle an unmarshaled and parsed
// request into a marshalable response. If the error is a *btcjson.RPCError
// or any of the above special error classes, the server will respond with
// the JSON-RPC appropiate error code. All other errors use the wallet
// catch-all error code, btcjson.ErrRPCWallet.
type requestHandler func(interface{}, *wallet.Wallet) (interface{}, error)
// requestHandlerChain is a requestHandler that also takes a parameter for
type requestHandlerChainRequired func(interface{}, *wallet.Wallet, *chain.RPCClient) (interface{}, error)
var rpcHandlers = map[string]struct {
handler requestHandler
handlerWithChain requestHandlerChainRequired
// Function variables cannot be compared against anything but nil, so
// use a boolean to record whether help generation is necessary. This
// is used by the tests to ensure that help can be generated for every
// implemented method.
//
// A single map and this bool is here is used rather than several maps
// for the unimplemented handlers so every method has exactly one
// handler function.
noHelp bool
}{
// Reference implementation wallet methods (implemented)
"addmultisigaddress": {handler: addMultiSigAddress},
"createmultisig": {handler: createMultiSig},
"dumpprivkey": {handler: dumpPrivKey},
"getaccount": {handler: getAccount},
"getaccountaddress": {handler: getAccountAddress},
"getaddressesbyaccount": {handler: getAddressesByAccount},
"getbalance": {handler: getBalance},
"getbestblockhash": {handler: getBestBlockHash},
"getblockcount": {handler: getBlockCount},
"getinfo": {handlerWithChain: getInfo},
"getnewaddress": {handler: getNewAddress},
"getrawchangeaddress": {handler: getRawChangeAddress},
"getreceivedbyaccount": {handler: getReceivedByAccount},
"getreceivedbyaddress": {handler: getReceivedByAddress},
"gettransaction": {handler: getTransaction},
"help": {handler: helpNoChainRPC, handlerWithChain: helpWithChainRPC},
"importprivkey": {handler: importPrivKey},
"keypoolrefill": {handler: keypoolRefill},
"listaccounts": {handler: listAccounts},
"listlockunspent": {handler: listLockUnspent},
"listreceivedbyaccount": {handler: listReceivedByAccount},
"listreceivedbyaddress": {handler: listReceivedByAddress},
"listsinceblock": {handlerWithChain: listSinceBlock},
"listtransactions": {handler: listTransactions},
"listunspent": {handler: listUnspent},
"lockunspent": {handler: lockUnspent},
"sendfrom": {handlerWithChain: sendFrom},
"sendmany": {handler: sendMany},
"sendtoaddress": {handler: sendToAddress},
"settxfee": {handler: setTxFee},
"signmessage": {handler: signMessage},
"signrawtransaction": {handlerWithChain: signRawTransaction},
"validateaddress": {handler: validateAddress},
"verifymessage": {handler: verifyMessage},
"walletlock": {handler: walletLock},
"walletpassphrase": {handler: walletPassphrase},
"walletpassphrasechange": {handler: walletPassphraseChange},
// Reference implementation methods (still unimplemented)
"backupwallet": {handler: unimplemented, noHelp: true},
"dumpwallet": {handler: unimplemented, noHelp: true},
"getwalletinfo": {handler: unimplemented, noHelp: true},
"importwallet": {handler: unimplemented, noHelp: true},
"listaddressgroupings": {handler: unimplemented, noHelp: true},
// Reference methods which can't be implemented by bchwallet due to
// design decision differences
"encryptwallet": {handler: unsupported, noHelp: true},
"move": {handler: unsupported, noHelp: true},
"setaccount": {handler: unsupported, noHelp: true},
// Extensions to the reference client JSON-RPC API
"createnewaccount": {handler: createNewAccount},
"getbestblock": {handler: getBestBlock},
// 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": {handler: getUnconfirmedBalance},
"listaddresstransactions": {handler: listAddressTransactions},
"listalltransactions": {handler: listAllTransactions},
"renameaccount": {handler: renameAccount},
"walletislocked": {handler: walletIsLocked},
}
// unimplemented handles an unimplemented RPC request with the
// appropiate error.
func unimplemented(interface{}, *wallet.Wallet) (interface{}, error) {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCUnimplemented,
Message: "Method unimplemented",
}
}
// unsupported handles a standard bitcoind RPC request which is
// unsupported by bchwallet due to design differences.
func unsupported(interface{}, *wallet.Wallet) (interface{}, error) {
return nil, &btcjson.RPCError{
Code: -1,
Message: "Request unsupported by btcwallet",
}
}
// 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{}, *btcjson.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(request *btcjson.Request, w *wallet.Wallet, chainClient chain.Interface) lazyHandler {
handlerData, ok := rpcHandlers[request.Method]
if ok && handlerData.handlerWithChain != nil && w != nil && chainClient != nil {
return func() (interface{}, *btcjson.RPCError) {
cmd, err := btcjson.UnmarshalCmd(request)
if err != nil {
return nil, btcjson.ErrRPCInvalidRequest
}
switch client := chainClient.(type) {
case *chain.RPCClient:
resp, err := handlerData.handlerWithChain(cmd,
w, client)
if err != nil {
return nil, jsonError(err)
}
return resp, nil
default:
return nil, &btcjson.RPCError{
Code: -1,
Message: "Chain RPC is inactive",
}
}
}
}
if ok && handlerData.handler != nil && w != nil {
return func() (interface{}, *btcjson.RPCError) {
cmd, err := btcjson.UnmarshalCmd(request)
if err != nil {
return nil, btcjson.ErrRPCInvalidRequest
}
resp, err := handlerData.handler(cmd, w)
if err != nil {
return nil, jsonError(err)
}
return resp, nil
}
}
// Fallback to RPC passthrough
return func() (interface{}, *btcjson.RPCError) {
if chainClient == nil {
return nil, &btcjson.RPCError{
Code: -1,
Message: "Chain RPC is inactive",
}
}
switch client := chainClient.(type) {
case *chain.RPCClient:
resp, err := client.RawRequest(request.Method,
request.Params)
if err != nil {
return nil, jsonError(err)
}
return &resp, nil
default:
return nil, &btcjson.RPCError{
Code: -1,
Message: "Chain RPC is inactive",
}
}
}
}
// 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) btcjson.Response {
idPtr := idPointer(id)
if err != nil {
return btcjson.Response{
ID: idPtr,
Error: jsonError(err),
}
}
resultBytes, err := json.Marshal(result)
if err != nil {
return btcjson.Response{
ID: idPtr,
Error: &btcjson.RPCError{
Code: btcjson.ErrRPCInternal.Code,
Message: "Unexpected error marshalling result",
},
}
}
return btcjson.Response{
ID: idPtr,
Result: json.RawMessage(resultBytes),
}
}
// jsonError creates a JSON-RPC error from the Go error.
func jsonError(err error) *btcjson.RPCError {
if err == nil {
return nil
}
code := btcjson.ErrRPCWallet
switch e := err.(type) {
case btcjson.RPCError:
return &e
case *btcjson.RPCError:
return e
case DeserializationError:
code = btcjson.ErrRPCDeserialization
case InvalidParameterError:
code = btcjson.ErrRPCInvalidParameter
case ParseError:
code = btcjson.ErrRPCParse.Code
case waddrmgr.ManagerError:
switch e.ErrorCode {
case waddrmgr.ErrWrongPassphrase:
code = btcjson.ErrRPCWalletPassphraseIncorrect
}
}
return &btcjson.RPCError{
Code: code,
Message: err.Error(),
}
}
// makeMultiSigScript is a helper function to combine common logic for
// AddMultiSig and CreateMultiSig.
func makeMultiSigScript(w *wallet.Wallet, keys []string, nRequired int) ([]byte, error) {
keysesPrecious := make([]*bchutil.AddressPubKey, len(keys))
// The address list will made up either of addreseses (pubkey hash), for
// which we need to look up the keys in wallet, straight pubkeys, or a
// mixture of the two.
for i, a := range keys {
// try to parse as pubkey address
a, err := decodeAddress(a, w.ChainParams())
if err != nil {
return nil, err
}
switch addr := a.(type) {
case *bchutil.AddressPubKey:
keysesPrecious[i] = addr
default:
pubKey, err := w.PubKeyForAddress(addr)
if err != nil {
return nil, err
}
pubKeyAddr, err := bchutil.NewAddressPubKey(
pubKey.SerializeCompressed(), w.ChainParams())
if err != nil {
return nil, err
}
keysesPrecious[i] = pubKeyAddr
}
}
return txscript.MultiSigScript(keysesPrecious, nRequired)
}
// addMultiSigAddress handles an addmultisigaddress request by adding a
// multisig address to the given wallet.
func addMultiSigAddress(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.AddMultisigAddressCmd)
// If an account is specified, ensure that is the imported account.
if cmd.Account != nil && *cmd.Account != waddrmgr.ImportedAddrAccountName {
return nil, &ErrNotImportedAccount
}
secp256k1Addrs := make([]bchutil.Address, len(cmd.Keys))
for i, k := range cmd.Keys {
addr, err := decodeAddress(k, w.ChainParams())
if err != nil {
return nil, ParseError{err}
}
secp256k1Addrs[i] = addr
}
script, err := w.MakeMultiSigScript(secp256k1Addrs, cmd.NRequired)
if err != nil {
return nil, err
}
p2shAddr, err := w.ImportP2SHRedeemScript(script)
if err != nil {
return nil, err
}
return p2shAddr.EncodeAddress(), nil
}
// createMultiSig handles an createmultisig request by returning a
// multisig address for the given inputs.
func createMultiSig(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.CreateMultisigCmd)
script, err := makeMultiSigScript(w, cmd.Keys, cmd.NRequired)
if err != nil {
return nil, ParseError{err}
}
address, err := bchutil.NewAddressScriptHash(script, w.ChainParams())
if err != nil {
// above is a valid script, shouldn't happen.
return nil, err
}
return btcjson.CreateMultiSigResult{
Address: address.EncodeAddress(),
RedeemScript: hex.EncodeToString(script),
}, nil
}
// dumpPrivKey handles a dumpprivkey request with the private key
// for a single address, or an appropiate error if the wallet
// is locked.
func dumpPrivKey(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.DumpPrivKeyCmd)
addr, err := decodeAddress(cmd.Address, w.ChainParams())
if err != nil {
return nil, err
}
key, err := w.DumpWIFPrivateKey(addr)
if waddrmgr.IsError(err, waddrmgr.ErrLocked) {
// Address was found, but the private key isn't
// accessible.
return nil, &ErrWalletUnlockNeeded
}
return key, err
}
// dumpWallet handles a dumpwallet request by returning all private
// keys in a wallet, or an appropiate error if the wallet is locked.
// TODO: finish this to match bitcoind by writing the dump to a file.
func dumpWallet(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
keys, err := w.DumpPrivKeys()
if waddrmgr.IsError(err, waddrmgr.ErrLocked) {
return nil, &ErrWalletUnlockNeeded
}
return keys, err
}
// getAddressesByAccount handles a getaddressesbyaccount request by returning
// all addresses for an account, or an error if the requested account does
// not exist.
func getAddressesByAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.GetAddressesByAccountCmd)
account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, cmd.Account)
if err != nil {
return nil, err
}
addrs, err := w.AccountAddresses(account)
if err != nil {
return nil, err
}
addrStrs := make([]string, len(addrs))
for i, a := range addrs {
addrStrs[i] = a.EncodeAddress()
}
return addrStrs, nil
}
// getBalance handles a getbalance request by returning the balance for an
// account (wallet), or an error if the requested account does not
// exist.
func getBalance(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.GetBalanceCmd)
var balance bchutil.Amount
var err error
accountName := "*"
if cmd.Account != nil {
accountName = *cmd.Account
}
if accountName == "*" {
balance, err = w.CalculateBalance(int32(*cmd.MinConf))
if err != nil {
return nil, err
}
} else {
var account uint32
account, err = w.AccountNumber(waddrmgr.KeyScopeBIP0044, accountName)
if err != nil {
return nil, err
}
bals, err := w.CalculateAccountBalances(account, int32(*cmd.MinConf))
if err != nil {
return nil, err
}
balance = bals.Spendable
}
return balance.ToBCH(), nil
}
// getBestBlock handles a getbestblock request by returning a JSON object
// with the height and hash of the most recently processed block.
func getBestBlock(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
blk := w.Manager.SyncedTo()
result := &btcjson.GetBestBlockResult{
Hash: blk.Hash.String(),
Height: blk.Height,
}
return result, nil
}
// getBestBlockHash handles a getbestblockhash request by returning the hash
// of the most recently processed block.
func getBestBlockHash(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
blk := w.Manager.SyncedTo()
return blk.Hash.String(), nil
}
// getBlockCount handles a getblockcount request by returning the chain height
// of the most recently processed block.
func getBlockCount(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
blk := w.Manager.SyncedTo()
return blk.Height, nil
}
// getInfo handles a getinfo request by returning the a structure containing
// information about the current state of bchwallet.
// exist.
func getInfo(icmd interface{}, w *wallet.Wallet, chainClient *chain.RPCClient) (interface{}, error) {
// Call down to bchd for all of the information in this command known
// by them.
info, err := chainClient.GetInfo()
if err != nil {
return nil, err
}
bal, err := w.CalculateBalance(1)
if err != nil {
return nil, err
}
// TODO(davec): This should probably have a database version as opposed
// to using the manager version.
info.WalletVersion = int32(waddrmgr.LatestMgrVersion)
info.Balance = bal.ToBCH()
info.PaytxFee = float64(txrules.DefaultRelayFeePerKb)
// We don't set the following since they don't make much sense in the
// wallet architecture:
// - unlocked_until
// - errors
return info, nil
}
func decodeAddress(s string, params *chaincfg.Params) (bchutil.Address, error) {
addr, err := bchutil.DecodeAddress(s, params)
if err != nil {
msg := fmt.Sprintf("Invalid address %q: decode failed with %#q", s, err)
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidAddressOrKey,
Message: msg,
}
}
if !addr.IsForNet(params) {
msg := fmt.Sprintf("Invalid address %q: not intended for use on %s",
addr, params.Name)
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidAddressOrKey,
Message: msg,
}
}
return addr, nil
}
// getAccount handles a getaccount request by returning the account name
// associated with a single address.
func getAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.GetAccountCmd)
addr, err := decodeAddress(cmd.Address, w.ChainParams())
if err != nil {
return nil, err
}
// Fetch the associated account
account, err := w.AccountOfAddress(addr)
if err != nil {
return nil, &ErrAddressNotInWallet
}
acctName, err := w.AccountName(waddrmgr.KeyScopeBIP0044, account)
if err != nil {
return nil, &ErrAccountNameNotFound
}
return acctName, nil
}
// getAccountAddress handles a getaccountaddress by returning the most
// recently-created chained address that has not yet been used (does not yet
// appear in the blockchain, or any tx that has arrived in the bchd mempool).
// If the most recently-requested address has been used, a new address (the
// next chained address in the keypool) is used. This can fail if the keypool
// runs out (and will return btcjson.ErrRPCWalletKeypoolRanOut if that happens).
func getAccountAddress(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.GetAccountAddressCmd)
account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, cmd.Account)
if err != nil {
return nil, err
}
addr, err := w.CurrentAddress(account, waddrmgr.KeyScopeBIP0044)
if err != nil {
return nil, err
}
return addr.EncodeAddress(), err
}
// getUnconfirmedBalance handles a getunconfirmedbalance extension request
// by returning the current unconfirmed balance of an account.
func getUnconfirmedBalance(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.GetUnconfirmedBalanceCmd)
acctName := "default"
if cmd.Account != nil {
acctName = *cmd.Account
}
account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, acctName)
if err != nil {
return nil, err
}
bals, err := w.CalculateAccountBalances(account, 1)
if err != nil {
return nil, err
}
return (bals.Total - bals.Spendable).ToBCH(), nil
}
// importPrivKey handles an importprivkey request by parsing
// a WIF-encoded private key and adding it to an account.
func importPrivKey(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.ImportPrivKeyCmd)
// Ensure that private keys are only imported to the correct account.
//
// Yes, Label is the account name.
if cmd.Label != nil && *cmd.Label != waddrmgr.ImportedAddrAccountName {
return nil, &ErrNotImportedAccount
}
wif, err := bchutil.DecodeWIF(cmd.PrivKey)
if err != nil {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidAddressOrKey,
Message: "WIF decode failed: " + err.Error(),
}
}
if !wif.IsForNet(w.ChainParams()) {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidAddressOrKey,
Message: "Key is not intended for " + w.ChainParams().Name,
}
}
// Import the private key, handling any errors.
_, err = w.ImportPrivateKey(waddrmgr.KeyScopeBIP0044, wif, nil, *cmd.Rescan)
switch {
case waddrmgr.IsError(err, waddrmgr.ErrDuplicateAddress):
// Do not return duplicate key errors to the client.
return nil, nil
case waddrmgr.IsError(err, waddrmgr.ErrLocked):
return nil, &ErrWalletUnlockNeeded
}
return nil, err
}
// keypoolRefill handles the keypoolrefill command. Since we handle the keypool
// automatically this does nothing since refilling is never manually required.
func keypoolRefill(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
return nil, nil
}
// createNewAccount handles a createnewaccount request by creating and
// returning a new account. If the last account has no transaction history
// as per BIP 0044 a new account cannot be created so an error will be returned.
func createNewAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.CreateNewAccountCmd)
// The wildcard * is reserved by the rpc server with the special meaning
// of "all accounts", so disallow naming accounts to this string.
if cmd.Account == "*" {
return nil, &ErrReservedAccountName
}
_, err := w.NextAccount(waddrmgr.KeyScopeBIP0044, cmd.Account)
if waddrmgr.IsError(err, waddrmgr.ErrLocked) {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCWalletUnlockNeeded,
Message: "Creating an account requires the wallet to be unlocked. " +
"Enter the wallet passphrase with walletpassphrase to unlock",
}
}
return nil, err
}
// renameAccount handles a renameaccount request by renaming an account.
// If the account does not exist an appropiate error will be returned.
func renameAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.RenameAccountCmd)
// The wildcard * is reserved by the rpc server with the special meaning
// of "all accounts", so disallow naming accounts to this string.
if cmd.NewAccount == "*" {
return nil, &ErrReservedAccountName
}
// Check that given account exists
account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, cmd.OldAccount)
if err != nil {
return nil, err
}
return nil, w.RenameAccount(waddrmgr.KeyScopeBIP0044, account, cmd.NewAccount)
}
// getNewAddress handles a getnewaddress request by returning a new
// address for an account. If the account does not exist an appropiate
// error is returned.
// TODO: Follow BIP 0044 and warn if number of unused addresses exceeds
// the gap limit.
func getNewAddress(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.GetNewAddressCmd)
acctName := "default"
if cmd.Account != nil {
acctName = *cmd.Account
}
account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, acctName)
if err != nil {
return nil, err
}
addr, err := w.NewAddress(account, waddrmgr.KeyScopeBIP0044)
if err != nil {
return nil, err
}
// Return the new payment address string.
return w.ChainParams().CashAddressPrefix + ":" + addr.EncodeAddress(), nil
}
// getRawChangeAddress handles a getrawchangeaddress request by creating
// and returning a new change address for an account.
//
// Note: bitcoind allows specifying the account as an optional parameter,
// but ignores the parameter.
func getRawChangeAddress(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.GetRawChangeAddressCmd)
acctName := "default"
if cmd.Account != nil {
acctName = *cmd.Account
}
account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, acctName)
if err != nil {
return nil, err
}
addr, err := w.NewChangeAddress(account, waddrmgr.KeyScopeBIP0044)
if err != nil {
return nil, err
}
// Return the new payment address string.
return addr.EncodeAddress(), nil
}
// getReceivedByAccount handles a getreceivedbyaccount request by returning
// the total amount received by addresses of an account.
func getReceivedByAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.GetReceivedByAccountCmd)
account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, cmd.Account)
if err != nil {
return nil, err
}
// TODO: This is more inefficient that it could be, but the entire
// algorithm is already dominated by reading every transaction in the
// wallet's history.
results, err := w.TotalReceivedForAccounts(
waddrmgr.KeyScopeBIP0044, int32(*cmd.MinConf),
)
if err != nil {
return nil, err
}
acctIndex := int(account)
if account == waddrmgr.ImportedAddrAccount {
acctIndex = len(results) - 1
}
return results[acctIndex].TotalReceived.ToBCH(), nil
}
// getReceivedByAddress handles a getreceivedbyaddress request by returning
// the total amount received by a single address.
func getReceivedByAddress(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.GetReceivedByAddressCmd)
addr, err := decodeAddress(cmd.Address, w.ChainParams())
if err != nil {
return nil, err
}
total, err := w.TotalReceivedForAddr(addr, int32(*cmd.MinConf))
if err != nil {
return nil, err
}
return total.ToBCH(), nil
}
// getTransaction handles a gettransaction request by returning details about
// a single transaction saved by wallet.
func getTransaction(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.GetTransactionCmd)
txHash, err := chainhash.NewHashFromStr(cmd.Txid)
if err != nil {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCDecodeHexString,
Message: "Transaction hash string decode failed: " + err.Error(),
}
}
details, err := wallet.UnstableAPI(w).TxDetails(txHash)
if err != nil {
return nil, err
}
if details == nil {
return nil, &ErrNoTransactionInfo
}
syncBlock := w.Manager.SyncedTo()
// TODO: The serialized transaction is already in the DB, so
// reserializing can be avoided here.
var txBuf bytes.Buffer
txBuf.Grow(details.MsgTx.SerializeSize())
err = details.MsgTx.Serialize(&txBuf)
if err != nil {
return nil, err
}
// TODO: Add a "generated" field to this result type. "generated":true
// is only added if the transaction is a coinbase.
ret := btcjson.GetTransactionResult{
TxID: cmd.Txid,
Hex: hex.EncodeToString(txBuf.Bytes()),
Time: details.Received.Unix(),
TimeReceived: details.Received.Unix(),
WalletConflicts: []string{}, // Not saved
//Generated: blockchain.IsCoinBaseTx(&details.MsgTx),
}
if details.Block.Height != -1 {
ret.BlockHash = details.Block.Hash.String()
ret.BlockTime = details.Block.Time.Unix()
ret.Confirmations = int64(confirms(details.Block.Height, syncBlock.Height))
}
var (
debitTotal bchutil.Amount
creditTotal bchutil.Amount // Excludes change
fee bchutil.Amount
feeF64 float64
)
for _, deb := range details.Debits {
debitTotal += deb.Amount
}
for _, cred := range details.Credits {
if !cred.Change {
creditTotal += cred.Amount
}
}
// Fee can only be determined if every input is a debit.
if len(details.Debits) == len(details.MsgTx.TxIn) {
var outputTotal bchutil.Amount
for _, output := range details.MsgTx.TxOut {
outputTotal += bchutil.Amount(output.Value)
}
fee = debitTotal - outputTotal
feeF64 = fee.ToBCH()
}
if len(details.Debits) == 0 {
// Credits must be set later, but since we know the full length
// of the details slice, allocate it with the correct cap.
ret.Details = make([]btcjson.GetTransactionDetailsResult, 0, len(details.Credits))
} else {
ret.Details = make([]btcjson.GetTransactionDetailsResult, 1, len(details.Credits)+1)
ret.Details[0] = btcjson.GetTransactionDetailsResult{
// Fields left zeroed:
// InvolvesWatchOnly
// Account
// Address
// Vout
//
// TODO(jrick): Address and Vout should always be set,
// but we're doing the wrong thing here by not matching
// core. Instead, gettransaction should only be adding
// details for transaction outputs, just like
// listtransactions (but using the short result format).
Category: "send",
Amount: (-debitTotal).ToBCH(), // negative since it is a send
Fee: &feeF64,
}
ret.Fee = feeF64
}
credCat := wallet.RecvCategory(details, syncBlock.Height, w.ChainParams()).String()
for _, cred := range details.Credits {
// Change is ignored.
if cred.Change {
continue
}
var address string
var accountName string
_, addrs, _, err := txscript.ExtractPkScriptAddrs(
details.MsgTx.TxOut[cred.Index].PkScript, w.ChainParams())
if err == nil && len(addrs) == 1 {
addr := addrs[0]
address = addr.EncodeAddress()
account, err := w.AccountOfAddress(addr)
if err == nil {
name, err := w.AccountName(waddrmgr.KeyScopeBIP0044, account)
if err == nil {
accountName = name
}
}
}
ret.Details = append(ret.Details, btcjson.GetTransactionDetailsResult{
// Fields left zeroed:
// InvolvesWatchOnly
// Fee
Account: accountName,
Address: address,
Category: credCat,
Amount: cred.Amount.ToBCH(),
Vout: cred.Index,
})
}
ret.Amount = creditTotal.ToBCH()
return ret, nil
}
// These generators create the following global variables in this package:
//
// var localeHelpDescs map[string]func() map[string]string
// var requestUsages string
//
// localeHelpDescs maps from locale strings (e.g. "en_US") to a function that
// builds a map of help texts for each RPC server method. This prevents help
// text maps for every locale map from being rooted and created during init.
// Instead, the appropiate function is looked up when help text is first needed
// using the current locale and saved to the global below for futher reuse.
//
// requestUsages contains single line usages for every supported request,
// separated by newlines. It is set during init. These usages are used for all
// locales.
//
//go:generate go run ../../internal/rpchelp/genrpcserverhelp.go legacyrpc
//go:generate gofmt -w rpcserverhelp.go
var helpDescs map[string]string
var helpDescsMu sync.Mutex // Help may execute concurrently, so synchronize access.
// helpWithChainRPC handles the help request when the RPC server has been
// associated with a consensus RPC client. The additional RPC client is used to
// include help messages for methods implemented by the consensus server via RPC
// passthrough.
func helpWithChainRPC(icmd interface{}, w *wallet.Wallet, chainClient *chain.RPCClient) (interface{}, error) {
return help(icmd, w, chainClient)
}
// helpNoChainRPC handles the help request when the RPC server has not been
// associated with a consensus RPC client. No help messages are included for
// passthrough requests.
func helpNoChainRPC(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
return help(icmd, w, nil)
}
// help handles the help request by returning one line usage of all available
// methods, or full help for a specific method. The chainClient is optional,
// and this is simply a helper function for the HelpNoChainRPC and
// HelpWithChainRPC handlers.
func help(icmd interface{}, w *wallet.Wallet, chainClient *chain.RPCClient) (interface{}, error) {
cmd := icmd.(*btcjson.HelpCmd)
// bchd returns different help messages depending on the kind of
// connection the client is using. Only methods availble to HTTP POST
// clients are available to be used by wallet clients, even though
// wallet itself is a websocket client to bchd. Therefore, create a
// POST client as needed.
//
// Returns nil if chainClient is currently nil or there is an error
// creating the client.
//
// This is hacky and is probably better handled by exposing help usage
// texts in a non-internal bchd package.
postClient := func() *rpcclient.Client {
if chainClient == nil {
return nil
}
c, err := chainClient.POSTClient()
if err != nil {
return nil
}
return c
}
if cmd.Command == nil || *cmd.Command == "" {
// Prepend chain server usage if it is available.
usages := requestUsages
client := postClient()
if client != nil {
rawChainUsage, err := client.RawRequest("help", nil)
var chainUsage string
if err == nil {
_ = json.Unmarshal([]byte(rawChainUsage), &chainUsage)
}
if chainUsage != "" {
usages = "Chain server usage:\n\n" + chainUsage + "\n\n" +
"Wallet server usage (overrides chain requests):\n\n" +
requestUsages
}
}