forked from btcsuite/btcd
-
Notifications
You must be signed in to change notification settings - Fork 27
/
rpcserver.go
4723 lines (4193 loc) · 145 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
// Copyright (c) 2019 Caleb James DeLisle
// 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"
"fmt"
"io"
"io/ioutil"
"math"
"math/big"
"math/rand"
"net"
"net/http"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
jsoniter "github.com/json-iterator/go"
"github.com/gorilla/websocket"
"github.com/pkt-cash/pktd/blockchain"
"github.com/pkt-cash/pktd/blockchain/indexers"
"github.com/pkt-cash/pktd/blockchain/packetcrypt"
"github.com/pkt-cash/pktd/blockchain/packetcrypt/difficulty"
"github.com/pkt-cash/pktd/btcec"
"github.com/pkt-cash/pktd/btcjson"
"github.com/pkt-cash/pktd/btcutil"
"github.com/pkt-cash/pktd/btcutil/er"
"github.com/pkt-cash/pktd/chaincfg"
"github.com/pkt-cash/pktd/chaincfg/chainhash"
"github.com/pkt-cash/pktd/chaincfg/globalcfg"
"github.com/pkt-cash/pktd/database"
"github.com/pkt-cash/pktd/mempool"
"github.com/pkt-cash/pktd/mining"
"github.com/pkt-cash/pktd/mining/cpuminer"
"github.com/pkt-cash/pktd/peer"
"github.com/pkt-cash/pktd/pktconfig/version"
"github.com/pkt-cash/pktd/pktlog/log"
"github.com/pkt-cash/pktd/txscript"
"github.com/pkt-cash/pktd/txscript/scriptbuilder"
"github.com/pkt-cash/pktd/wire"
"github.com/pkt-cash/pktd/wire/constants"
"github.com/pkt-cash/pktd/wire/protocol"
"github.com/pkt-cash/pktd/wire/ruleerror"
)
// 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
// 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
)
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(
scriptbuilder.NewScriptBuilder().
AddData([]byte(mining.DefaultCoinbaseFlags)))),
}
// 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"}
)
type commandHandler func(*rpcServer, interface{}, <-chan struct{}) (interface{}, er.R)
// 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,
"configureminingpayouts": handleConfigureMiningPayouts,
"createrawtransaction": handleCreateRawTransaction,
"debuglevel": handleDebugLevel,
"decoderawtransaction": handleDecodeRawTransaction,
"decodescript": handleDecodeScript,
"estimatefee": handleEstimateFee,
"estimatesmartfee": handleEstimateSmartFee,
"generate": handleGenerate,
"getaddednodeinfo": handleGetAddedNodeInfo,
"getbestblock": handleGetBestBlock,
"getbestblockhash": handleGetBestBlockHash,
"getblock": handleGetBlock,
"getblockchaininfo": handleGetBlockChainInfo,
"getblockcount": handleGetBlockCount,
"getblockhash": handleGetBlockHash,
"getblockheader": handleGetBlockHeader,
"getblocktemplate": handleGetBlockTemplate,
"getcfilter": handleGetCFilter,
"getcfilterheader": handleGetCFilterHeader,
"getconnectioncount": handleGetConnectionCount,
"getcurrentnet": handleGetCurrentNet,
"getdifficulty": handleGetDifficulty,
"getgenerate": handleGetGenerate,
"gethashespersec": handleGetHashesPerSec,
"getheaders": handleGetHeaders,
"getinfo": handleGetInfo,
"getmempoolinfo": handleGetMempoolInfo,
"getmininginfo": handleGetMiningInfo,
"getminingpayouts": handleGetMiningPayouts,
"getnettotals": handleGetNetTotals,
"getnetworkhashps": handleGetNetworkHashPS,
"getnetworkinfo": handleGetNetworkInfo,
"getnetworksteward": handleGetNetworkSteward,
"getpeerinfo": handleGetPeerInfo,
"getrawmempool": handleGetRawMempool,
"getrawblocktemplate": handleGetRawBlockTemplate,
"checkpcshare": handleCheckPcShare,
"checkpcann": handleCheckPcAnn,
"getrawtransaction": handleGetRawTransaction,
"gettxout": handleGetTxOut,
"help": handleHelp,
"node": handleNode,
"ping": handlePing,
"echo": handleEcho,
"searchrawtransactions": handleSearchRawTransactions,
"sendrawtransaction": handleSendRawTransaction,
"setgenerate": handleSetGenerate,
"stop": handleStop,
"submitblock": handleSubmitBlock,
"uptime": handleUptime,
"validateaddress": handleValidateAddress,
"verifychain": handleVerifyChain,
"verifymessage": handleVerifyMessage,
"version": handleVersion,
}
// list of commands that we recognize, but for which pktd has no support because
// it lacks support for wallet functionality. For these commands the user
// should ask a connected instance of pktwallet.
var rpcAskWallet = map[string]struct{}{
"addmultisigaddress": {},
"addp2shscript": {},
"createencryptedwallet": {},
"createmultisig": {},
"dumpprivkey": {},
"getbalance": {},
"getnewaddress": {},
"getreceivedbyaddress": {},
"gettransaction": {},
"gettxoutsetinfo": {},
"getunconfirmedbalance": {},
"importprivkey": {},
"listlockunspent": {},
"listreceivedbyaddress": {},
"listsinceblock": {},
"listtransactions": {},
"listunspent": {},
"lockunspent": {},
"sendfrom": {},
"sendmany": {},
"sendtoaddress": {},
"sendvote": {},
"settxfee": {},
"signmessage": {},
"signrawtransaction": {},
"walletlock": {},
"walletpassphrase": {},
"walletpassphrasechange": {},
"walletmempool": {},
}
// Commands that are currently unimplemented, but should ultimately be.
var rpcUnimplemented = map[string]struct{}{
"getchaintips": {},
"getmempoolentry": {},
"getnetworkinfo": {},
"getwork": {},
"invalidateblock": {},
"preciousblock": {},
"reconsiderblock": {},
}
// 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": {},
"getcfilter": {},
"getcfilterheader": {},
"getcurrentnet": {},
"getdifficulty": {},
"getheaders": {},
"getinfo": {},
"getnettotals": {},
"getnetworkhashps": {},
"getrawmempool": {},
"getrawtransaction": {},
"gettxout": {},
"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 *scriptbuilder.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(err er.R, context string) er.R {
return btcjson.NewRPCError(btcjson.ErrRPCInternal, context, err)
}
// 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) er.R {
return btcjson.NewRPCError(btcjson.ErrRPCDecodeHexString,
fmt.Sprintf("Argument must be hexadecimal string (not %q)",
gotHex), nil)
}
// 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) er.R {
return btcjson.NewRPCError(btcjson.ErrRPCNoTxInfo,
fmt.Sprintf("No information available about transaction %v",
txHash), nil)
}
// 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
withPayAddresses bool
}
// 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{}, er.R) {
return nil, btcjson.NewRPCError(
btcjson.ErrRPCUnimplemented,
"Command unimplemented",
nil,
)
}
// 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 pktwallet.
func handleAskWallet(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, er.R) {
return nil, btcjson.NewRPCError(
btcjson.ErrRPCNoWallet,
"This RPC requires --wallet",
nil,
)
}
// handleAddNode handles addnode commands.
func handleAddNode(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, er.R) {
c := cmd.(*btcjson.AddNodeCmd)
addr := normalizeAddress(c.Addr, s.cfg.ChainParams.DefaultPort)
var err er.R
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.NewRPCError(
btcjson.ErrRPCInvalidParameter,
"invalid subcommand for addnode",
nil,
)
}
if err != nil {
return nil, btcjson.NewRPCError(
btcjson.ErrRPCInvalidParameter,
"",
err,
)
}
// no data returned unless an error.
return nil, nil
}
// handleNode handles node commands.
func handleNode(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, er.R) {
c := cmd.(*btcjson.NodeCmd)
var addr string
var nodeID uint64
var err er.R
var errN 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.NewRPCError(
btcjson.ErrRPCInvalidParameter,
"invalid address or node ID",
nil,
)
}
}
if err != nil && peerExists(s.cfg.ConnMgr, addr, int32(nodeID)) {
return nil, btcjson.NewRPCError(
btcjson.ErrRPCMisc,
"can't disconnect a permanent peer, use remove",
nil,
)
}
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.NewRPCError(
btcjson.ErrRPCInvalidParameter,
"invalid address or node ID",
nil,
)
}
}
if err != nil && peerExists(s.cfg.ConnMgr, addr, int32(nodeID)) {
return nil, btcjson.NewRPCError(
btcjson.ErrRPCMisc,
"can't remove a temporary peer, use disconnect",
nil,
)
}
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.NewRPCError(
btcjson.ErrRPCInvalidParameter,
"invalid subcommand for node connect",
nil,
)
}
default:
return nil, btcjson.NewRPCError(
btcjson.ErrRPCInvalidParameter,
"invalid subcommand for node",
nil,
)
}
if err != nil {
return nil, btcjson.NewRPCError(
btcjson.ErrRPCInvalidParameter,
"",
err,
)
}
// 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, er.R) {
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, context)
}
return hex.EncodeToString(buf.Bytes()), nil
}
// handleCreateRawTransaction handles createrawtransaction commands.
func handleCreateRawTransaction(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, er.R) {
c := cmd.(*btcjson.CreateRawTransactionCmd)
// Validate the locktime, if given.
if c.LockTime != nil &&
(*c.LockTime < 0 || *c.LockTime > int64(constants.MaxTxInSequenceNum)) {
return nil, btcjson.NewRPCError(
btcjson.ErrRPCInvalidParameter,
"Locktime out of range",
nil,
)
}
// Add all transaction inputs to a new transaction after performing
// some validity checks.
mtx := wire.NewMsgTx(constants.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 = constants.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 || float64(amount*float64(globalcfg.SatoshiPerBitcoin())) > float64(btcutil.MaxUnits()) {
return nil, btcjson.NewRPCError(
btcjson.ErrRPCType,
"Invalid amount",
nil,
)
}
// Decode the provided address.
addr, err := btcutil.DecodeAddress(encodedAddr, params)
if err != nil {
return nil, btcjson.NewRPCError(
btcjson.ErrRPCInvalidAddressOrKey,
"Invalid address or key",
err,
)
}
if !addr.IsForNet(params) {
return nil, btcjson.NewRPCError(
btcjson.ErrRPCInvalidAddressOrKey,
"Invalid address: "+encodedAddr+" is for the wrong network",
nil,
)
}
// 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, context)
}
// Convert the amount to satoshi.
satoshi, err := globalcfg.NewAmount(amount)
if err != nil {
context := "Failed to convert amount"
return nil, internalRPCError(err, context)
}
txOut := wire.NewTxOut(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{}, er.R) {
return "Done.", nil
}
// witnessToHex formats the passed witness stack as a slice of hex-encoded
// strings to be used in a JSON response.
func witnessToHex(witness wire.TxWitness) []string {
// Ensure nil is returned when there are no entries versus an empty
// slice so it can properly be omitted as necessary.
if len(witness) == 0 {
return nil
}
result := make([]string, 0, len(witness))
for _, wit := range witness {
result = append(result, hex.EncodeToString(wit))
}
return result
}
// 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 {
encodedAddr := txscript.PkScriptToAddress(v.PkScript, chainParams).EncodeAddress()
if len(filterAddrMap) == 0 {
} else if _, exists := filterAddrMap[encodedAddr]; !exists {
continue
}
var vout btcjson.Vout
vout.N = uint32(i)
vout.ValueCoins = btcutil.Amount(v.Value).ToBTC()
vout.Svalue = strconv.FormatInt(v.Value, 10)
vout.Address = encodedAddr
vote(&vout.Vote, v.PkScript, chainParams)
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, er.R) {
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))),
Vin: createVinList(mtx, chainParams),
Vout: createVoutList(mtx, chainParams, nil),
Version: 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{}, er.R) {
c := cmd.(*btcjson.DecodeRawTransactionCmd)
// Deserialize the transaction.
hexStr := c.HexTx
if len(hexStr)%2 != 0 {
hexStr = "0" + hexStr
}
serializedTx, errr := hex.DecodeString(hexStr)
if errr != nil {
return nil, rpcDecodeHexError(hexStr)
}
var mtx wire.MsgTx
err := mtx.Deserialize(bytes.NewReader(serializedTx))
if err != nil {
return nil, btcjson.NewRPCError(
btcjson.ErrRPCDeserialization, "TX decode failed", err)
}
xtra := false
if c.VinExtra != nil && *c.VinExtra {
xtra = true
}
vin, err := createVinListPrevOut(s, &mtx, s.cfg.ChainParams, xtra, nil)
if err != nil {
return nil, err
}
sfee := "unknown"
if xtra {
failed := false
fee := int64(0)
for _, input := range vin {
if input.PrevOut == nil {
failed = true
break
}
n, errr := strconv.ParseInt(input.PrevOut.Svalue, 10, 64)
if errr != nil {
return nil, er.E(errr)
}
fee += n
}
for _, out := range mtx.TxOut {
fee -= out.Value
}
if !failed {
sfee = strconv.FormatInt(fee, 10)
}
}
// Create and return the result.
txReply := btcjson.TxRawDecodeResult{
Txid: mtx.TxHash().String(),
Version: mtx.Version,
Locktime: mtx.LockTime,
Size: int32(mtx.SerializeSize()),
Vsize: int32(mempool.GetTxVirtualSize(btcutil.NewTx(&mtx))),
Vin: vin,
Vout: createVoutList(&mtx, s.cfg.ChainParams, nil),
Sfee: sfee,
}
return txReply, nil
}
func vote(voteOut **btcjson.Vote, script []byte, params *chaincfg.Params) {
voteFor, voteAgainst := txscript.ElectionGetVotesForAgainst(script)
if voteFor == nil && voteAgainst == nil {
return
}
v := btcjson.Vote{}
if voteFor != nil {
v.For = txscript.PkScriptToAddress(voteFor, params).EncodeAddress()
}
if voteAgainst != nil {
v.Against = txscript.PkScriptToAddress(voteAgainst, params).EncodeAddress()
}
*voteOut = &v
}
// handleDecodeScript handles decodescript commands.
func handleDecodeScript(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, er.R) {
c := cmd.(*btcjson.DecodeScriptCmd)
// Convert the hex script to bytes.
hexStr := c.HexScript
if len(hexStr)%2 != 0 {
hexStr = "0" + hexStr
}
script, errr := hex.DecodeString(hexStr)
if errr != 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 additinal 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, context)
}
// Generate and return the reply.
reply := btcjson.DecodeScriptResult{
Asm: disbuf,
ReqSigs: int32(reqSigs),
Type: scriptClass.String(),
Addresses: addresses,
}
vote(&reply.Vote, script, s.cfg.ChainParams)
if scriptClass != txscript.ScriptHashTy {
reply.P2sh = p2sh.EncodeAddress()
}
return reply, nil
}
// handleEstimateFee handles estimatefee commands.
func handleEstimateFee(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, er.R) {
c := cmd.(*btcjson.EstimateFeeCmd)
if s.cfg.FeeEstimator == nil {
return nil, er.New("Fee estimation disabled")
}
if c.NumBlocks <= 0 {
return -1.0, er.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
}
func handleEstimateSmartFee(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, er.R) {
c := cmd.(*btcjson.EstimateSmartFeeCmd)
if s.cfg.FeeEstimator == nil {
return nil, er.New("Fee estimation disabled")
}
conservitive := true
if c.EstimateMode != nil && *c.EstimateMode == btcjson.EstimateModeEconomical {
conservitive = false
}
if c.ConfTarget <= 0 {
return -1.0, er.New("Parameter NumBlocks must be positive")
}
return s.cfg.FeeEstimator.EstimateSmartFee(uint32(c.ConfTarget), conservitive), nil
}
// handleGenerate handles generate commands.
func handleGenerate(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, er.R) {
// Respond with an error if there are no addresses to pay the
// created blocks to.
if len(cfg.miningAddrs) == 0 {
return nil, btcjson.NewRPCError(
btcjson.ErrRPCInternal,
"No payment addresses specified via --miningaddr",
nil,
)
}
// 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.NewRPCError(
btcjson.ErrRPCDifficulty,
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),
nil,
)
}
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.NewRPCError(
btcjson.ErrRPCInternal,
"Please request a nonzero number of blocks to generate.",
nil,
)
}
// Create a reply
reply := make([]string, c.NumBlocks)
blockHashes, err := s.cfg.CPUMiner.GenerateNBlocks(c.NumBlocks)
if err != nil {
return nil, btcjson.NewRPCError(
btcjson.ErrRPCInternal,
"",
err,
)
}
// 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{}, er.R) {
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.NewRPCError(
btcjson.ErrRPCClientNodeNotAdded,
"Node has not been added",
nil,
)
}
}
// 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
// DNS lookup the address. If it fails, just use the host.
switch {
case net.ParseIP(host) != nil:
ipList = make([]string, 1)
ipList[0] = host
default:
ips, err := pktdLookup(host)
if err != nil {
ipList = make([]string, 1)
ipList[0] = host
break
}
ipList = make([]string, 0, len(ips))
for _, ip := range ips {
ipList = append(ipList, ip.String())
}
}
// Add the addresses and connection info to the result.
addrs := make([]btcjson.GetAddedNodeInfoResultAddr, 0, len(ipList))
for _, ip := range ipList {
var addr btcjson.GetAddedNodeInfoResultAddr
addr.Address = ip
addr.Connected = "false"
if ip == host && peer.Connected() {
addr.Connected = directionString(peer.Inbound())
}
addrs = append(addrs, addr)
}
result.Addresses = &addrs
results = append(results, &result)