forked from btcsuite/btcd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpcserver.go
4911 lines (4334 loc) · 154 KB
/
rpcserver.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) 2015-2017 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"math/big"
"math/rand"
"net"
"net/http"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/blockchain/indexers"
"github.com/btcsuite/btcd/btcec/v2/ecdsa"
"github.com/btcsuite/btcd/btcjson"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/mempool"
"github.com/btcsuite/btcd/mining"
"github.com/btcsuite/btcd/mining/cpuminer"
"github.com/btcsuite/btcd/peer"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/websocket"
)
// API version constants
const (
jsonrpcSemverString = "1.3.0"
jsonrpcSemverMajor = 1
jsonrpcSemverMinor = 3
jsonrpcSemverPatch = 0
)
const (
// rpcAuthTimeoutSeconds is the number of seconds a connection to the
// RPC server is allowed to stay open without authenticating before it
// is closed.
rpcAuthTimeoutSeconds = 10
// uint256Size is the number of bytes needed to represent an unsigned
// 256-bit integer.
uint256Size = 32
// gbtNonceRange is two 32-bit big-endian hexadecimal integers which
// represent the valid ranges of nonces returned by the getblocktemplate
// RPC.
gbtNonceRange = "00000000ffffffff"
// gbtRegenerateSeconds is the number of seconds that must pass before
// a new template is generated when the previous block hash has not
// changed and there have been changes to the available transactions
// in the memory pool.
gbtRegenerateSeconds = 60
// maxProtocolVersion is the max protocol version the server supports.
maxProtocolVersion = 70002
// defaultMaxFeeRate is the default value to use(0.1 BTC/kvB) when the
// `MaxFee` field is not set when calling `testmempoolaccept`.
defaultMaxFeeRate = 0.1
)
var (
// gbtMutableFields are the manipulations the server allows to be made
// to block templates generated by the getblocktemplate RPC. It is
// declared here to avoid the overhead of creating the slice on every
// invocation for constant data.
gbtMutableFields = []string{
"time", "transactions/add", "prevblock", "coinbase/append",
}
// gbtCoinbaseAux describes additional data that miners should include
// in the coinbase signature script. It is declared here to avoid the
// overhead of creating a new object on every invocation for constant
// data.
gbtCoinbaseAux = &btcjson.GetBlockTemplateResultAux{
Flags: hex.EncodeToString(builderScript(txscript.
NewScriptBuilder().
AddData([]byte(mining.CoinbaseFlags)))),
}
// gbtCapabilities describes additional capabilities returned with a
// block template generated by the getblocktemplate RPC. It is
// declared here to avoid the overhead of creating the slice on every
// invocation for constant data.
gbtCapabilities = []string{"proposal"}
// JSON 2.0 batched request prefix
batchedRequestPrefix = []byte("[")
)
// Errors
var (
// ErrRPCUnimplemented is an error returned to RPC clients when the
// provided command is recognized, but not implemented.
ErrRPCUnimplemented = &btcjson.RPCError{
Code: btcjson.ErrRPCUnimplemented,
Message: "Command unimplemented",
}
// ErrRPCNoWallet is an error returned to RPC clients when the provided
// command is recognized as a wallet command.
ErrRPCNoWallet = &btcjson.RPCError{
Code: btcjson.ErrRPCNoWallet,
Message: "This implementation does not implement wallet commands",
}
)
type commandHandler func(*rpcServer, interface{}, <-chan struct{}) (interface{}, error)
// rpcHandlers maps RPC command strings to appropriate handler functions.
// This is set by init because help references rpcHandlers and thus causes
// a dependency loop.
var rpcHandlers map[string]commandHandler
var rpcHandlersBeforeInit = map[string]commandHandler{
"addnode": handleAddNode,
"createrawtransaction": handleCreateRawTransaction,
"debuglevel": handleDebugLevel,
"decoderawtransaction": handleDecodeRawTransaction,
"decodescript": handleDecodeScript,
"estimatefee": handleEstimateFee,
"generate": handleGenerate,
"getaddednodeinfo": handleGetAddedNodeInfo,
"getbestblock": handleGetBestBlock,
"getbestblockhash": handleGetBestBlockHash,
"getblock": handleGetBlock,
"getblockchaininfo": handleGetBlockChainInfo,
"getblockcount": handleGetBlockCount,
"getblockhash": handleGetBlockHash,
"getblockheader": handleGetBlockHeader,
"getblocktemplate": handleGetBlockTemplate,
"getchaintips": handleGetChainTips,
"getcfilter": handleGetCFilter,
"getcfilterheader": handleGetCFilterHeader,
"getconnectioncount": handleGetConnectionCount,
"getcurrentnet": handleGetCurrentNet,
"getdifficulty": handleGetDifficulty,
"getgenerate": handleGetGenerate,
"gethashespersec": handleGetHashesPerSec,
"getheaders": handleGetHeaders,
"getinfo": handleGetInfo,
"getmempoolinfo": handleGetMempoolInfo,
"getmininginfo": handleGetMiningInfo,
"getnettotals": handleGetNetTotals,
"getnetworkhashps": handleGetNetworkHashPS,
"getnodeaddresses": handleGetNodeAddresses,
"getpeerinfo": handleGetPeerInfo,
"getrawmempool": handleGetRawMempool,
"getrawtransaction": handleGetRawTransaction,
"gettxout": handleGetTxOut,
"help": handleHelp,
"invalidateblock": handleInvalidateBlock,
"node": handleNode,
"ping": handlePing,
"reconsiderblock": handleReconsiderBlock,
"searchrawtransactions": handleSearchRawTransactions,
"sendrawtransaction": handleSendRawTransaction,
"setgenerate": handleSetGenerate,
"signmessagewithprivkey": handleSignMessageWithPrivKey,
"stop": handleStop,
"submitblock": handleSubmitBlock,
"uptime": handleUptime,
"validateaddress": handleValidateAddress,
"verifychain": handleVerifyChain,
"verifymessage": handleVerifyMessage,
"version": handleVersion,
"testmempoolaccept": handleTestMempoolAccept,
"gettxspendingprevout": handleGetTxSpendingPrevOut,
}
// list of commands that we recognize, but for which btcd has no support because
// it lacks support for wallet functionality. For these commands the user
// should ask a connected instance of btcwallet.
var rpcAskWallet = map[string]struct{}{
"addmultisigaddress": {},
"backupwallet": {},
"createencryptedwallet": {},
"createmultisig": {},
"dumpprivkey": {},
"dumpwallet": {},
"encryptwallet": {},
"getaccount": {},
"getaccountaddress": {},
"getaddressesbyaccount": {},
"getbalance": {},
"getnewaddress": {},
"getrawchangeaddress": {},
"getreceivedbyaccount": {},
"getreceivedbyaddress": {},
"gettransaction": {},
"gettxoutsetinfo": {},
"getunconfirmedbalance": {},
"getwalletinfo": {},
"importprivkey": {},
"importwallet": {},
"keypoolrefill": {},
"listaccounts": {},
"listaddressgroupings": {},
"listlockunspent": {},
"listreceivedbyaccount": {},
"listreceivedbyaddress": {},
"listsinceblock": {},
"listtransactions": {},
"listunspent": {},
"lockunspent": {},
"move": {},
"sendfrom": {},
"sendmany": {},
"sendtoaddress": {},
"setaccount": {},
"settxfee": {},
"signmessage": {},
"signrawtransaction": {},
"walletlock": {},
"walletpassphrase": {},
"walletpassphrasechange": {},
}
// Commands that are currently unimplemented, but should ultimately be.
var rpcUnimplemented = map[string]struct{}{
"estimatepriority": {},
"getmempoolentry": {},
"getnetworkinfo": {},
"getwork": {},
"preciousblock": {},
}
// Commands that are available to a limited user
var rpcLimited = map[string]struct{}{
// Websockets commands
"loadtxfilter": {},
"notifyblocks": {},
"notifynewtransactions": {},
"notifyreceived": {},
"notifyspent": {},
"rescan": {},
"rescanblocks": {},
"session": {},
// Websockets AND HTTP/S commands
"help": {},
// HTTP/S-only commands
"createrawtransaction": {},
"decoderawtransaction": {},
"decodescript": {},
"estimatefee": {},
"getbestblock": {},
"getbestblockhash": {},
"getblock": {},
"getblockcount": {},
"getblockhash": {},
"getblockheader": {},
"getchaintips": {},
"getcfilter": {},
"getcfilterheader": {},
"getcurrentnet": {},
"getdifficulty": {},
"getheaders": {},
"getinfo": {},
"getnettotals": {},
"getnetworkhashps": {},
"getrawmempool": {},
"getrawtransaction": {},
"gettxout": {},
"invalidateblock": {},
"reconsiderblock": {},
"searchrawtransactions": {},
"sendrawtransaction": {},
"submitblock": {},
"uptime": {},
"validateaddress": {},
"verifymessage": {},
"version": {},
}
// builderScript is a convenience function which is used for hard-coded scripts
// built with the script builder. Any errors are converted to a panic since it
// is only, and must only, be used with hard-coded, and therefore, known good,
// scripts.
func builderScript(builder *txscript.ScriptBuilder) []byte {
script, err := builder.Script()
if err != nil {
panic(err)
}
return script
}
// internalRPCError is a convenience function to convert an internal error to
// an RPC error with the appropriate code set. It also logs the error to the
// RPC server subsystem since internal errors really should not occur. The
// context parameter is only used in the log message and may be empty if it's
// not needed.
func internalRPCError(errStr, context string) *btcjson.RPCError {
logStr := errStr
if context != "" {
logStr = context + ": " + errStr
}
rpcsLog.Error(logStr)
return btcjson.NewRPCError(btcjson.ErrRPCInternal.Code, errStr)
}
// rpcDecodeHexError is a convenience function for returning a nicely formatted
// RPC error which indicates the provided hex string failed to decode.
func rpcDecodeHexError(gotHex string) *btcjson.RPCError {
return btcjson.NewRPCError(btcjson.ErrRPCDecodeHexString,
fmt.Sprintf("Argument must be hexadecimal string (not %q)",
gotHex))
}
// rpcNoTxInfoError is a convenience function for returning a nicely formatted
// RPC error which indicates there is no information available for the provided
// transaction hash.
func rpcNoTxInfoError(txHash *chainhash.Hash) *btcjson.RPCError {
return btcjson.NewRPCError(btcjson.ErrRPCNoTxInfo,
fmt.Sprintf("No information available about transaction %v",
txHash))
}
// gbtWorkState houses state that is used in between multiple RPC invocations to
// getblocktemplate.
type gbtWorkState struct {
sync.Mutex
lastTxUpdate time.Time
lastGenerated time.Time
prevHash *chainhash.Hash
minTimestamp time.Time
template *mining.BlockTemplate
notifyMap map[chainhash.Hash]map[int64]chan struct{}
timeSource blockchain.MedianTimeSource
}
// newGbtWorkState returns a new instance of a gbtWorkState with all internal
// fields initialized and ready to use.
func newGbtWorkState(timeSource blockchain.MedianTimeSource) *gbtWorkState {
return &gbtWorkState{
notifyMap: make(map[chainhash.Hash]map[int64]chan struct{}),
timeSource: timeSource,
}
}
// handleUnimplemented is the handler for commands that should ultimately be
// supported but are not yet implemented.
func handleUnimplemented(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
return nil, ErrRPCUnimplemented
}
// handleAskWallet is the handler for commands that are recognized as valid, but
// are unable to answer correctly since it involves wallet state.
// These commands will be implemented in btcwallet.
func handleAskWallet(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
return nil, ErrRPCNoWallet
}
// handleAddNode handles addnode commands.
func handleAddNode(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
c := cmd.(*btcjson.AddNodeCmd)
addr := normalizeAddress(c.Addr, s.cfg.ChainParams.DefaultPort)
var err error
switch c.SubCmd {
case "add":
err = s.cfg.ConnMgr.Connect(addr, true)
case "remove":
err = s.cfg.ConnMgr.RemoveByAddr(addr)
case "onetry":
err = s.cfg.ConnMgr.Connect(addr, false)
default:
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidParameter,
Message: "invalid subcommand for addnode",
}
}
if err != nil {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidParameter,
Message: err.Error(),
}
}
// no data returned unless an error.
return nil, nil
}
// handleNode handles node commands.
func handleNode(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
c := cmd.(*btcjson.NodeCmd)
var addr string
var nodeID uint64
var errN, err error
params := s.cfg.ChainParams
switch c.SubCmd {
case "disconnect":
// If we have a valid uint disconnect by node id. Otherwise,
// attempt to disconnect by address, returning an error if a
// valid IP address is not supplied.
if nodeID, errN = strconv.ParseUint(c.Target, 10, 32); errN == nil {
err = s.cfg.ConnMgr.DisconnectByID(int32(nodeID))
} else {
if _, _, errP := net.SplitHostPort(c.Target); errP == nil || net.ParseIP(c.Target) != nil {
addr = normalizeAddress(c.Target, params.DefaultPort)
err = s.cfg.ConnMgr.DisconnectByAddr(addr)
} else {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidParameter,
Message: "invalid address or node ID",
}
}
}
if err != nil && peerExists(s.cfg.ConnMgr, addr, int32(nodeID)) {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCMisc,
Message: "can't disconnect a permanent peer, use remove",
}
}
case "remove":
// If we have a valid uint disconnect by node id. Otherwise,
// attempt to disconnect by address, returning an error if a
// valid IP address is not supplied.
if nodeID, errN = strconv.ParseUint(c.Target, 10, 32); errN == nil {
err = s.cfg.ConnMgr.RemoveByID(int32(nodeID))
} else {
if _, _, errP := net.SplitHostPort(c.Target); errP == nil || net.ParseIP(c.Target) != nil {
addr = normalizeAddress(c.Target, params.DefaultPort)
err = s.cfg.ConnMgr.RemoveByAddr(addr)
} else {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidParameter,
Message: "invalid address or node ID",
}
}
}
if err != nil && peerExists(s.cfg.ConnMgr, addr, int32(nodeID)) {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCMisc,
Message: "can't remove a temporary peer, use disconnect",
}
}
case "connect":
addr = normalizeAddress(c.Target, params.DefaultPort)
// Default to temporary connections.
subCmd := "temp"
if c.ConnectSubCmd != nil {
subCmd = *c.ConnectSubCmd
}
switch subCmd {
case "perm", "temp":
err = s.cfg.ConnMgr.Connect(addr, subCmd == "perm")
default:
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidParameter,
Message: "invalid subcommand for node connect",
}
}
default:
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidParameter,
Message: "invalid subcommand for node",
}
}
if err != nil {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidParameter,
Message: err.Error(),
}
}
// no data returned unless an error.
return nil, nil
}
// peerExists determines if a certain peer is currently connected given
// information about all currently connected peers. Peer existence is
// determined using either a target address or node id.
func peerExists(connMgr rpcserverConnManager, addr string, nodeID int32) bool {
for _, p := range connMgr.ConnectedPeers() {
if p.ToPeer().ID() == nodeID || p.ToPeer().Addr() == addr {
return true
}
}
return false
}
// messageToHex serializes a message to the wire protocol encoding using the
// latest protocol version and returns a hex-encoded string of the result.
func messageToHex(msg wire.Message) (string, error) {
var buf bytes.Buffer
if err := msg.BtcEncode(&buf, maxProtocolVersion, wire.WitnessEncoding); err != nil {
context := fmt.Sprintf("Failed to encode msg of type %T", msg)
return "", internalRPCError(err.Error(), context)
}
return hex.EncodeToString(buf.Bytes()), nil
}
// handleCreateRawTransaction handles createrawtransaction commands.
func handleCreateRawTransaction(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
c := cmd.(*btcjson.CreateRawTransactionCmd)
// Validate the locktime, if given.
if c.LockTime != nil &&
(*c.LockTime < 0 || *c.LockTime > int64(wire.MaxTxInSequenceNum)) {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidParameter,
Message: "Locktime out of range",
}
}
// Add all transaction inputs to a new transaction after performing
// some validity checks.
mtx := wire.NewMsgTx(wire.TxVersion)
for _, input := range c.Inputs {
txHash, err := chainhash.NewHashFromStr(input.Txid)
if err != nil {
return nil, rpcDecodeHexError(input.Txid)
}
prevOut := wire.NewOutPoint(txHash, input.Vout)
txIn := wire.NewTxIn(prevOut, []byte{}, nil)
if c.LockTime != nil && *c.LockTime != 0 {
txIn.Sequence = wire.MaxTxInSequenceNum - 1
}
mtx.AddTxIn(txIn)
}
// Add all transaction outputs to the transaction after performing
// some validity checks.
params := s.cfg.ChainParams
for encodedAddr, amount := range c.Amounts {
// Ensure amount is in the valid range for monetary amounts.
if amount <= 0 || amount*btcutil.SatoshiPerBitcoin > btcutil.MaxSatoshi {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCType,
Message: "Invalid amount",
}
}
// Decode the provided address.
addr, err := btcutil.DecodeAddress(encodedAddr, params)
if err != nil {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidAddressOrKey,
Message: "Invalid address or key: " + err.Error(),
}
}
// Ensure the address is one of the supported types and that
// the network encoded with the address matches the network the
// server is currently on.
switch addr.(type) {
case *btcutil.AddressPubKeyHash:
case *btcutil.AddressScriptHash:
default:
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidAddressOrKey,
Message: "Invalid address or key",
}
}
if !addr.IsForNet(params) {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidAddressOrKey,
Message: "Invalid address: " + encodedAddr +
" is for the wrong network",
}
}
// Create a new script which pays to the provided address.
pkScript, err := txscript.PayToAddrScript(addr)
if err != nil {
context := "Failed to generate pay-to-address script"
return nil, internalRPCError(err.Error(), context)
}
// Convert the amount to satoshi.
satoshi, err := btcutil.NewAmount(amount)
if err != nil {
context := "Failed to convert amount"
return nil, internalRPCError(err.Error(), context)
}
txOut := wire.NewTxOut(int64(satoshi), pkScript)
mtx.AddTxOut(txOut)
}
// Set the Locktime, if given.
if c.LockTime != nil {
mtx.LockTime = uint32(*c.LockTime)
}
// Return the serialized and hex-encoded transaction. Note that this
// is intentionally not directly returning because the first return
// value is a string and it would result in returning an empty string to
// the client instead of nothing (nil) in the case of an error.
mtxHex, err := messageToHex(mtx)
if err != nil {
return nil, err
}
return mtxHex, nil
}
// handleDebugLevel handles debuglevel commands.
func handleDebugLevel(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
c := cmd.(*btcjson.DebugLevelCmd)
// Special show command to list supported subsystems.
if c.LevelSpec == "show" {
return fmt.Sprintf("Supported subsystems %v",
supportedSubsystems()), nil
}
err := parseAndSetDebugLevels(c.LevelSpec)
if err != nil {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidParams.Code,
Message: err.Error(),
}
}
return "Done.", nil
}
// createVinList returns a slice of JSON objects for the inputs of the passed
// transaction.
func createVinList(mtx *wire.MsgTx) []btcjson.Vin {
// Coinbase transactions only have a single txin by definition.
vinList := make([]btcjson.Vin, len(mtx.TxIn))
if blockchain.IsCoinBaseTx(mtx) {
txIn := mtx.TxIn[0]
vinList[0].Coinbase = hex.EncodeToString(txIn.SignatureScript)
vinList[0].Sequence = txIn.Sequence
vinList[0].Witness = txIn.Witness.ToHexStrings()
return vinList
}
for i, txIn := range mtx.TxIn {
// The disassembled string will contain [error] inline
// if the script doesn't fully parse, so ignore the
// error here.
disbuf, _ := txscript.DisasmString(txIn.SignatureScript)
vinEntry := &vinList[i]
vinEntry.Txid = txIn.PreviousOutPoint.Hash.String()
vinEntry.Vout = txIn.PreviousOutPoint.Index
vinEntry.Sequence = txIn.Sequence
vinEntry.ScriptSig = &btcjson.ScriptSig{
Asm: disbuf,
Hex: hex.EncodeToString(txIn.SignatureScript),
}
if mtx.HasWitness() {
vinEntry.Witness = txIn.Witness.ToHexStrings()
}
}
return vinList
}
// createVoutList returns a slice of JSON objects for the outputs of the passed
// transaction.
func createVoutList(mtx *wire.MsgTx, chainParams *chaincfg.Params, filterAddrMap map[string]struct{}) []btcjson.Vout {
voutList := make([]btcjson.Vout, 0, len(mtx.TxOut))
for i, v := range mtx.TxOut {
// The disassembled string will contain [error] inline if the
// script doesn't fully parse, so ignore the error here.
disbuf, _ := txscript.DisasmString(v.PkScript)
// Ignore the error here since an error means the script
// couldn't parse and there is no additional information about
// it anyways.
scriptClass, addrs, reqSigs, _ := txscript.ExtractPkScriptAddrs(
v.PkScript, chainParams)
// Encode the addresses while checking if the address passes the
// filter when needed.
passesFilter := len(filterAddrMap) == 0
encodedAddrs := make([]string, len(addrs))
for j, addr := range addrs {
encodedAddr := addr.EncodeAddress()
encodedAddrs[j] = encodedAddr
// No need to check the map again if the filter already
// passes.
if passesFilter {
continue
}
if _, exists := filterAddrMap[encodedAddr]; exists {
passesFilter = true
}
}
if !passesFilter {
continue
}
var vout btcjson.Vout
vout.N = uint32(i)
vout.Value = btcutil.Amount(v.Value).ToBTC()
vout.ScriptPubKey.Addresses = encodedAddrs
vout.ScriptPubKey.Asm = disbuf
vout.ScriptPubKey.Hex = hex.EncodeToString(v.PkScript)
vout.ScriptPubKey.Type = scriptClass.String()
vout.ScriptPubKey.ReqSigs = int32(reqSigs)
// Address is defined when there's a single well-defined
// receiver address. To spend the output a signature for this,
// and only this, address is required.
if len(encodedAddrs) == 1 && reqSigs <= 1 {
vout.ScriptPubKey.Address = encodedAddrs[0]
}
voutList = append(voutList, vout)
}
return voutList
}
// createTxRawResult converts the passed transaction and associated parameters
// to a raw transaction JSON object.
func createTxRawResult(chainParams *chaincfg.Params, mtx *wire.MsgTx,
txHash string, blkHeader *wire.BlockHeader, blkHash string,
blkHeight int32, chainHeight int32) (*btcjson.TxRawResult, error) {
mtxHex, err := messageToHex(mtx)
if err != nil {
return nil, err
}
txReply := &btcjson.TxRawResult{
Hex: mtxHex,
Txid: txHash,
Hash: mtx.WitnessHash().String(),
Size: int32(mtx.SerializeSize()),
Vsize: int32(mempool.GetTxVirtualSize(btcutil.NewTx(mtx))),
Weight: int32(blockchain.GetTransactionWeight(btcutil.NewTx(mtx))),
Vin: createVinList(mtx),
Vout: createVoutList(mtx, chainParams, nil),
Version: uint32(mtx.Version),
LockTime: mtx.LockTime,
}
if blkHeader != nil {
// This is not a typo, they are identical in bitcoind as well.
txReply.Time = blkHeader.Timestamp.Unix()
txReply.Blocktime = blkHeader.Timestamp.Unix()
txReply.BlockHash = blkHash
txReply.Confirmations = uint64(1 + chainHeight - blkHeight)
}
return txReply, nil
}
// handleDecodeRawTransaction handles decoderawtransaction commands.
func handleDecodeRawTransaction(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
c := cmd.(*btcjson.DecodeRawTransactionCmd)
// Deserialize the transaction.
hexStr := c.HexTx
if len(hexStr)%2 != 0 {
hexStr = "0" + hexStr
}
serializedTx, err := hex.DecodeString(hexStr)
if err != nil {
return nil, rpcDecodeHexError(hexStr)
}
var mtx wire.MsgTx
err = mtx.Deserialize(bytes.NewReader(serializedTx))
if err != nil {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCDeserialization,
Message: "TX decode failed: " + err.Error(),
}
}
// Create and return the result.
txReply := btcjson.TxRawDecodeResult{
Txid: mtx.TxHash().String(),
Version: mtx.Version,
Locktime: mtx.LockTime,
Vin: createVinList(&mtx),
Vout: createVoutList(&mtx, s.cfg.ChainParams, nil),
}
return txReply, nil
}
// handleDecodeScript handles decodescript commands.
func handleDecodeScript(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
c := cmd.(*btcjson.DecodeScriptCmd)
// Convert the hex script to bytes.
hexStr := c.HexScript
if len(hexStr)%2 != 0 {
hexStr = "0" + hexStr
}
script, err := hex.DecodeString(hexStr)
if err != nil {
return nil, rpcDecodeHexError(hexStr)
}
// The disassembled string will contain [error] inline if the script
// doesn't fully parse, so ignore the error here.
disbuf, _ := txscript.DisasmString(script)
// Get information about the script.
// Ignore the error here since an error means the script couldn't parse
// and there is no additional information about it anyways.
scriptClass, addrs, reqSigs, _ := txscript.ExtractPkScriptAddrs(script,
s.cfg.ChainParams)
addresses := make([]string, len(addrs))
for i, addr := range addrs {
addresses[i] = addr.EncodeAddress()
}
// Convert the script itself to a pay-to-script-hash address.
p2sh, err := btcutil.NewAddressScriptHash(script, s.cfg.ChainParams)
if err != nil {
context := "Failed to convert script to pay-to-script-hash"
return nil, internalRPCError(err.Error(), context)
}
// Generate and return the reply.
reply := btcjson.DecodeScriptResult{
Asm: disbuf,
ReqSigs: int32(reqSigs),
Type: scriptClass.String(),
Addresses: addresses,
}
if scriptClass != txscript.ScriptHashTy {
reply.P2sh = p2sh.EncodeAddress()
}
// Address is defined when there's a single well-defined
// receiver address. To spend the output a signature for this,
// and only this, address is required.
if len(addresses) == 1 && reqSigs <= 1 {
reply.Address = addresses[0]
}
return reply, nil
}
// handleEstimateFee handles estimatefee commands.
func handleEstimateFee(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
c := cmd.(*btcjson.EstimateFeeCmd)
if s.cfg.FeeEstimator == nil {
return nil, errors.New("Fee estimation disabled")
}
if c.NumBlocks <= 0 {
return -1.0, errors.New("Parameter NumBlocks must be positive")
}
feeRate, err := s.cfg.FeeEstimator.EstimateFee(uint32(c.NumBlocks))
if err != nil {
return -1.0, err
}
// Convert to satoshis per kb.
return float64(feeRate), nil
}
// handleGenerate handles generate commands.
func handleGenerate(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
// Respond with an error if there are no addresses to pay the
// created blocks to.
if len(cfg.miningAddrs) == 0 {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInternal.Code,
Message: "No payment addresses specified " +
"via --miningaddr",
}
}
// Respond with an error if there's virtually 0 chance of mining a block
// with the CPU.
if !s.cfg.ChainParams.GenerateSupported {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCDifficulty,
Message: fmt.Sprintf("No support for `generate` on "+
"the current network, %s, as it's unlikely to "+
"be possible to mine a block with the CPU.",
s.cfg.ChainParams.Net),
}
}
c := cmd.(*btcjson.GenerateCmd)
// Respond with an error if the client is requesting 0 blocks to be generated.
if c.NumBlocks == 0 {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInternal.Code,
Message: "Please request a nonzero number of blocks to generate.",
}
}
// Create a reply
reply := make([]string, c.NumBlocks)
blockHashes, err := s.cfg.CPUMiner.GenerateNBlocks(c.NumBlocks)
if err != nil {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInternal.Code,
Message: err.Error(),
}
}
// Mine the correct number of blocks, assigning the hex representation of the
// hash of each one to its place in the reply.
for i, hash := range blockHashes {
reply[i] = hash.String()
}
return reply, nil
}
// handleGetAddedNodeInfo handles getaddednodeinfo commands.
func handleGetAddedNodeInfo(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
c := cmd.(*btcjson.GetAddedNodeInfoCmd)
// Retrieve a list of persistent (added) peers from the server and
// filter the list of peers per the specified address (if any).
peers := s.cfg.ConnMgr.PersistentPeers()
if c.Node != nil {
node := *c.Node
found := false
for i, peer := range peers {
if peer.ToPeer().Addr() == node {
peers = peers[i : i+1]
found = true
}
}
if !found {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCClientNodeNotAdded,
Message: "Node has not been added",
}
}
}
// Without the dns flag, the result is just a slice of the addresses as
// strings.
if !c.DNS {
results := make([]string, 0, len(peers))
for _, peer := range peers {
results = append(results, peer.ToPeer().Addr())
}
return results, nil
}
// With the dns flag, the result is an array of JSON objects which
// include the result of DNS lookups for each peer.
results := make([]*btcjson.GetAddedNodeInfoResult, 0, len(peers))
for _, rpcPeer := range peers {
// Set the "address" of the peer which could be an ip address
// or a domain name.
peer := rpcPeer.ToPeer()
var result btcjson.GetAddedNodeInfoResult
result.AddedNode = peer.Addr()
result.Connected = btcjson.Bool(peer.Connected())
// Split the address into host and port portions so we can do
// a DNS lookup against the host. When no port is specified in
// the address, just use the address as the host.
host, _, err := net.SplitHostPort(peer.Addr())
if err != nil {
host = peer.Addr()
}
var ipList []string
switch {
case net.ParseIP(host) != nil, strings.HasSuffix(host, ".onion"):