This repository has been archived by the owner on Aug 7, 2023. It is now read-only.
forked from decred/dcrd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpcserver.go
6385 lines (5651 loc) · 199 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-2016 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/elliptic"
"crypto/sha256"
"crypto/subtle"
"crypto/tls"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"math"
"math/big"
"math/rand"
"net"
"net/http"
"os"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/btcsuite/websocket"
"github.com/decred/bitset"
"github.com/decred/dcrd/blockchain"
"github.com/decred/dcrd/blockchain/stake"
"github.com/decred/dcrd/chaincfg"
"github.com/decred/dcrd/chaincfg/chainec"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/database"
"github.com/decred/dcrd/dcrjson"
"github.com/decred/dcrd/mempool"
"github.com/decred/dcrd/mining"
"github.com/decred/dcrd/txscript"
"github.com/decred/dcrd/wire"
"github.com/decred/dcrutil"
)
// API version constants
const (
jsonrpcSemverString = "3.1.0"
jsonrpcSemverMajor = 3
jsonrpcSemverMinor = 1
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
// getworkDataLen is the length of the data field of the getwork RPC.
// It consists of the serialized block header plus the internal blake256
// padding. The internal blake256 padding consists of a single 1 bit
// followed by zeros and a final 1 bit in order to pad the message out
// to 56 bytes followed by length of the message in bits encoded as a
// big-endian uint64 (8 bytes). Thus, the resulting length is a
// multiple of the blake256 block size (64 bytes). Given the padding
// requires at least a 1 bit and 64 bits for the padding, the following
// converts the block header length and hash block size to bits in order
// to ensure the correct number of hash blocks are calculated and then
// multiplies the result by the block hash block size in bytes.
getworkDataLen = (1 + ((wire.MaxBlockHeaderPayload*8 + 65) /
(chainhash.HashBlockSize * 8))) * chainhash.HashBlockSize
// getworkExpirationDiff is the number of blocks below the current
// best block in height to begin pruning out old block work from
// the template pool.
getworkExpirationDiff = 3
// 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
// merkleRootPairSize
merkleRootPairSize = 64
// sstxCommitmentString is the string to insert when a verbose
// transaction output's pkscript type is a ticket commitment.
sstxCommitmentString = "sstxcommitment"
// maxSigOpsPerTx is the maximum number of signature operations
// in a single transaction we will relay or mine. It is a fraction
// of the max signature operations for a block.
//
// NOTE: This is being added while syncing upstream because the code in
// the RPC server here is referencing the variable even though it most
// definitely shouldn't be. It is a policy limit regarding what should
// be relayed or mined and thus should only apply in the mempool and/or
// possibly the mining code.
maxSigOpsPerTx = blockchain.MaxSigOpsPerBlock / 5
)
var (
// blake256Pad is the extra blake256 internal padding needed for the
// data of the getwork RPC. It is set in the init routine since it is
// based on the size of the block header and requires a bit of
// calculation.
blake256Pad []byte
// 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 = &dcrjson.GetBlockTemplateResultAux{
Flags: hex.EncodeToString(builderScript(txscript.
NewScriptBuilder().AddData([]byte(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"}
)
// Errors
var (
// ErrRPCUnimplemented is an error returned to RPC clients when the
// provided command is recognized, but not implemented.
ErrRPCUnimplemented = &dcrjson.RPCError{
Code: dcrjson.ErrRPCUnimplemented,
Message: "Command unimplemented",
}
// ErrRPCNoWallet is an error returned to RPC clients when the provided
// command is recognized as a wallet command.
ErrRPCNoWallet = &dcrjson.RPCError{
Code: dcrjson.ErrRPCNoWallet,
Message: "This implementation does not implement wallet commands",
}
// ErrInvalidLongPoll is an internal error code to indicate that
// longpollid is not formated properly.
ErrInvalidLongPoll = errors.New("invalid longpollid format")
)
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,
"createrawsstx": handleCreateRawSStx,
"createrawssgentx": handleCreateRawSSGenTx,
"createrawssrtx": handleCreateRawSSRtx,
"createrawtransaction": handleCreateRawTransaction,
"debuglevel": handleDebugLevel,
"decoderawtransaction": handleDecodeRawTransaction,
"decodescript": handleDecodeScript,
"estimatefee": handleEstimateFee,
"estimatestakediff": handleEstimateStakeDiff,
"existsaddress": handleExistsAddress,
"existsaddresses": handleExistsAddresses,
"existsmissedtickets": handleExistsMissedTickets,
"existsexpiredtickets": handleExistsExpiredTickets,
"existsliveticket": handleExistsLiveTicket,
"existslivetickets": handleExistsLiveTickets,
"existsmempooltxs": handleExistsMempoolTxs,
"generate": handleGenerate,
"getaddednodeinfo": handleGetAddedNodeInfo,
"getbestblock": handleGetBestBlock,
"getbestblockhash": handleGetBestBlockHash,
"getblock": handleGetBlock,
"getblockcount": handleGetBlockCount,
"getblockhash": handleGetBlockHash,
"getblockheader": handleGetBlockHeader,
"getblocksubsidy": handleGetBlockSubsidy,
"getcoinsupply": handleGetCoinSupply,
"getconnectioncount": handleGetConnectionCount,
"getcurrentnet": handleGetCurrentNet,
"getdifficulty": handleGetDifficulty,
"getgenerate": handleGetGenerate,
"gethashespersec": handleGetHashesPerSec,
"getheaders": handleGetHeaders,
"getinfo": handleGetInfo,
"getmempoolinfo": handleGetMempoolInfo,
"getmininginfo": handleGetMiningInfo,
"getnettotals": handleGetNetTotals,
"getnetworkhashps": handleGetNetworkHashPS,
"getpeerinfo": handleGetPeerInfo,
"getrawmempool": handleGetRawMempool,
"getrawtransaction": handleGetRawTransaction,
"getstakedifficulty": handleGetStakeDifficulty,
"getstakeversioninfo": handleGetStakeVersionInfo,
"getstakeversions": handleGetStakeVersions,
"getticketpoolvalue": handleGetTicketPoolValue,
"getvoteinfo": handleGetVoteInfo,
"gettxout": handleGetTxOut,
"getwork": handleGetWork,
"help": handleHelp,
"livetickets": handleLiveTickets,
"missedtickets": handleMissedTickets,
"node": handleNode,
"ping": handlePing,
"searchrawtransactions": handleSearchRawTransactions,
"rebroadcastmissed": handleRebroadcastMissed,
"rebroadcastwinners": handleRebroadcastWinners,
"sendrawtransaction": handleSendRawTransaction,
"setgenerate": handleSetGenerate,
"stop": handleStop,
"submitblock": handleSubmitBlock,
"ticketfeeinfo": handleTicketFeeInfo,
"ticketsforaddress": handleTicketsForAddress,
"ticketvwap": handleTicketVWAP,
"txfeeinfo": handleTxFeeInfo,
"validateaddress": handleValidateAddress,
"verifychain": handleVerifyChain,
"verifymessage": handleVerifyMessage,
"version": handleVersion,
}
// list of commands that we recognize, but for which dcrd has no support because
// it lacks support for wallet functionality. For these commands the user
// should ask a connected instance of dcrwallet.
var rpcAskWallet = map[string]struct{}{
"accountaddressindex": {},
"accountsyncaddressindex": {},
"addmultisigaddress": {},
"addticket": {},
"backupwallet": {},
"createencryptedwallet": {},
"createmultisig": {},
"dumpprivkey": {},
"dumpwallet": {},
"encryptwallet": {},
"getaccount": {},
"getaccountaddress": {},
"getaddressesbyaccount": {},
"getbalance": {},
"getnewaddress": {},
"getrawchangeaddress": {},
"getreceivedbyaccount": {},
"getreceivedbyaddress": {},
"getstakeinfo": {},
"getvotechoices": {},
"gettransaction": {},
"gettxoutsetinfo": {},
"getunconfirmedbalance": {},
"getwalletinfo": {},
"importprivkey": {},
"importwallet": {},
"keypoolrefill": {},
"listaccounts": {},
"listaddressgroupings": {},
"listlockunspent": {},
"listreceivedbyaccount": {},
"listreceivedbyaddress": {},
"listsinceblock": {},
"listtransactions": {},
"listunspent": {},
"lockunspent": {},
"move": {},
"rescanwallet": {},
"revoketickets": {},
"sendfrom": {},
"sendmany": {},
"sendtoaddress": {},
"setaccount": {},
"setvotechoice": {},
"settxfee": {},
"signmessage": {},
"signrawtransaction": {},
"stakepooluserinfo": {},
"walletinfo": {},
"walletlock": {},
"walletpassphrase": {},
"walletpassphrasechange": {},
}
// Commands that are currently unimplemented, but should ultimately be.
var rpcUnimplemented = map[string]struct{}{
"estimatefee": {},
"estimatepriority": {},
"getblocktemplate": {},
"getblockchaininfo": {},
"getchaintips": {},
"getnetworkinfo": {},
}
// Commands that are available to a limited user
var rpcLimited = map[string]struct{}{
// Websockets commands
"notifyblocks": {},
"notifynewtransactions": {},
"notifyreceived": {},
"notifyspent": {},
"rescan": {},
"session": {},
// Websockets AND HTTP/S commands
"help": {},
// HTTP/S-only commands
"createrawtransaction": {},
"decoderawtransaction": {},
"decodescript": {},
"getbestblock": {},
"getbestblockhash": {},
"getblock": {},
"getblockcount": {},
"getblockhash": {},
"getcurrentnet": {},
"getdifficulty": {},
"getinfo": {},
"getnettotals": {},
"getnetworkhashps": {},
"getrawmempool": {},
"getrawtransaction": {},
"gettxout": {},
"searchrawtransactions": {},
"sendrawtransaction": {},
"submitblock": {},
"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
}
// rpcInternalError 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 rpcInternalError(errStr, context string) *dcrjson.RPCError {
logStr := errStr
if context != "" {
logStr = context + ": " + errStr
}
rpcsLog.Error(logStr)
return dcrjson.NewRPCError(dcrjson.ErrRPCInternal.Code, errStr)
}
// rpcInvalidError is a convenience function to convert an invalid parameter
// error to an RPC error with the appropriate code set.
func rpcInvalidError(fmtStr string, args ...interface{}) *dcrjson.RPCError {
return dcrjson.NewRPCError(dcrjson.ErrRPCInvalidParameter,
fmt.Sprintf(fmtStr, args...))
}
// rpcDeserializetionError is a convenience function to convert a
// deserialization error to an RPC error with the appropriate code set.
func rpcDeserializationError(fmtStr string, args ...interface{}) *dcrjson.RPCError {
return dcrjson.NewRPCError(dcrjson.ErrRPCDeserialization,
fmt.Sprintf(fmtStr, args...))
}
// rpcAddressKeyError is a convenience function to convert an address/key 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 rpcAddressKeyError(fmtStr string, args ...interface{}) *dcrjson.RPCError {
return dcrjson.NewRPCError(dcrjson.ErrRPCInvalidAddressOrKey,
fmt.Sprintf(fmtStr, args...))
}
// 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) *dcrjson.RPCError {
return dcrjson.NewRPCError(dcrjson.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) *dcrjson.RPCError {
return dcrjson.NewRPCError(dcrjson.ErrRPCNoTxInfo,
fmt.Sprintf("No information available about transaction %v",
txHash))
}
// rpcMiscError is a convenience function for returning a nicely formatted RPC
// error which indicates there is a unquantifiable error. Use this sparingly;
// misc return codes are a cop out.
func rpcMiscError(message string) *dcrjson.RPCError {
return dcrjson.NewRPCError(dcrjson.ErrRPCMisc, message)
}
// workStateBlockInfo houses information about how to reconstruct a block given
// its template and signature script.
type workStateBlockInfo struct {
msgBlock *wire.MsgBlock
pkScript []byte
}
// workState houses state that is used in between multiple RPC invocations to
// getwork.
type workState struct {
sync.Mutex
lastTxUpdate time.Time
lastGenerated time.Time
prevHash *chainhash.Hash
msgBlock *wire.MsgBlock
extraNonce uint64
}
// newWorkState returns a new instance of a workState with all internal fields
// initialized and ready to use.
func newWorkState() *workState {
return &workState{}
}
// 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 *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 dcrwallet.
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.(*dcrjson.AddNodeCmd)
addr := normalizeAddress(c.Addr, activeNetParams.DefaultPort)
var err error
switch c.SubCmd {
case "add":
err = s.server.ConnectNode(addr, true)
case "remove":
err = s.server.RemoveNodeByAddr(addr)
case "onetry":
err = s.server.ConnectNode(addr, false)
default:
return nil, rpcInvalidError("Invalid subcommand for addnode")
}
if err != nil {
return nil, rpcInvalidError("%v: %v", c.SubCmd, err)
}
// 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.(*dcrjson.NodeCmd)
var addr string
var nodeID uint64
var errN, err error
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.server.DisconnectNodeByID(int32(nodeID))
} else {
if _, _, errP := net.SplitHostPort(c.Target); errP == nil ||
net.ParseIP(c.Target) != nil {
addr = normalizeAddress(c.Target, activeNetParams.DefaultPort)
err = s.server.DisconnectNodeByAddr(addr)
} else {
return nil, rpcInvalidError("%v: Invalid "+
"address or node ID", c.SubCmd)
}
}
if err != nil &&
peerExists(s.server.Peers(), addr, int32(nodeID)) {
return nil, rpcMiscError("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.server.RemoveNodeByID(int32(nodeID))
} else {
if _, _, errP := net.SplitHostPort(c.Target); errP == nil ||
net.ParseIP(c.Target) != nil {
addr = normalizeAddress(c.Target, activeNetParams.DefaultPort)
err = s.server.RemoveNodeByAddr(addr)
} else {
return nil, rpcInvalidError("%v: invalid "+
"address or node ID", c.SubCmd)
}
}
if err != nil &&
peerExists(s.server.Peers(), addr, int32(nodeID)) {
return nil, rpcMiscError("can't remove a temporary " +
"peer, use disconnect")
}
case "connect":
addr = normalizeAddress(c.Target, activeNetParams.DefaultPort)
// Default to temporary connections.
subCmd := "temp"
if c.ConnectSubCmd != nil {
subCmd = *c.ConnectSubCmd
}
switch subCmd {
case "perm", "temp":
err = s.server.ConnectNode(addr, subCmd == "perm")
default:
return nil, rpcInvalidError("%v: invalid subcommand "+
"for node connect", subCmd)
}
default:
return nil, rpcInvalidError("%v: invalid subcommand for node",
c.SubCmd)
}
if err != nil {
return nil, rpcInvalidError("%v: %v", c.SubCmd, 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(peers []*serverPeer, addr string, nodeID int32) bool {
for _, p := range peers {
if p.ID() == nodeID || p.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); err != nil {
context := fmt.Sprintf("Failed to encode msg of type %T", msg)
return "", rpcInternalError(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.(*dcrjson.CreateRawTransactionCmd)
// Validate the locktime, if given.
if c.LockTime != nil &&
(*c.LockTime < 0 ||
*c.LockTime > int64(wire.MaxTxInSequenceNum)) {
return nil, rpcInvalidError("Locktime out of range")
}
// Add all transaction inputs to a new transaction after performing
// some validity checks.
mtx := wire.NewMsgTx()
for _, input := range c.Inputs {
txHash, err := chainhash.NewHashFromStr(input.Txid)
if err != nil {
return nil, rpcDecodeHexError(input.Txid)
}
if !(input.Tree == wire.TxTreeRegular ||
input.Tree == wire.TxTreeStake) {
return nil, rpcInvalidError("Tx tree must be regular " +
"or stake")
}
prevOut := wire.NewOutPoint(txHash, input.Vout, input.Tree)
txIn := wire.NewTxIn(prevOut, []byte{})
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.
for encodedAddr, amount := range c.Amounts {
// Ensure amount is in the valid range for monetary amounts.
if amount <= 0 || amount > dcrutil.MaxAmount {
return nil, rpcInvalidError("Invalid amount: 0 >= %v "+
"> %v", amount, dcrutil.MaxAmount)
}
// Decode the provided address.
addr, err := dcrutil.DecodeAddress(encodedAddr,
activeNetParams.Params)
if err != nil {
return nil, rpcAddressKeyError("Could not decode "+
"address: %v", err)
}
// 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 *dcrutil.AddressPubKeyHash:
case *dcrutil.AddressScriptHash:
default:
return nil, rpcAddressKeyError("Invalid type: %T", addr)
}
if !addr.IsForNet(s.server.chainParams) {
return nil, rpcAddressKeyError("Wrong network: %v",
addr)
}
// Create a new script which pays to the provided address.
pkScript, err := txscript.PayToAddrScript(addr)
if err != nil {
return nil, rpcInternalError(err.Error(),
"Pay to adress script")
}
atomic, err := dcrutil.NewAmount(amount)
if err != nil {
return nil, rpcInternalError(err.Error(),
"New amount")
}
txOut := wire.NewTxOut(int64(atomic), 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
}
// handleCreateRawSStx handles createrawsstx commands.
func handleCreateRawSStx(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
c := cmd.(*dcrjson.CreateRawSStxCmd)
// Basic sanity checks for the information coming from the cmd.
if len(c.Inputs) != len(c.COuts) {
return nil, rpcInvalidError("Number of inputs should be equal "+
"to the number of future commitment/change outs for "+
"any sstx; %v inputs given, but %v COuts",
len(c.Inputs), len(c.COuts))
}
if len(c.Amount) != 1 {
return nil, rpcInvalidError("Only one SSGen tagged output is "+
"allowed per sstx; len ssgenout %v", len(c.Amount))
}
// Add all transaction inputs to a new transaction after performing
// some validity checks.
mtx := wire.NewMsgTx()
for _, input := range c.Inputs {
txHash, err := chainhash.NewHashFromStr(input.Txid)
if err != nil {
return nil, rpcDecodeHexError(input.Txid)
}
if input.Vout < 0 {
return nil, rpcInvalidError("Vout must be positive")
}
if !(input.Tree == wire.TxTreeRegular ||
input.Tree == wire.TxTreeStake) {
rpcInvalidError("Tx tree must be regular or stake")
}
prevOut := wire.NewOutPoint(txHash, input.Vout, input.Tree)
txIn := wire.NewTxIn(prevOut, []byte{})
mtx.AddTxIn(txIn)
}
// Add all transaction outputs to the transaction after performing
// some validity checks.
amtTicket := int64(0)
for encodedAddr, amount := range c.Amount {
// Ensure amount is in the valid range for monetary amounts.
if amount <= 0 || amount > dcrutil.MaxAmount {
return nil, rpcInvalidError("Invalid SSTx commitment "+
"amount: 0 >= %v > %v", amount,
dcrutil.MaxAmount)
}
// Decode the provided address.
addr, err := dcrutil.DecodeAddress(encodedAddr,
activeNetParams.Params)
if err != nil {
return nil, rpcAddressKeyError("Could not decode "+
"address: %v", err)
}
// 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 *dcrutil.AddressPubKeyHash:
default:
return nil, rpcAddressKeyError("Invalid address type: "+
"%T", addr)
}
if !addr.IsForNet(s.server.chainParams) {
return nil, rpcAddressKeyError("Wrong network: %v",
addr)
}
// Create a new script which pays to the provided address with an
// SStx tagged output.
pkScript, err := txscript.PayToSStx(addr)
if err != nil {
return nil, rpcInternalError(err.Error(),
"Could not create TX script")
}
txOut := wire.NewTxOut(amount, pkScript)
mtx.AddTxOut(txOut)
amtTicket += amount
}
// Calculated the commitment amounts, then create the
// addresses and payout proportions as null data
// outputs.
inputAmts := make([]int64, len(c.Inputs))
for i, input := range c.Inputs {
inputAmts[i] = input.Amt
}
changeAmts := make([]int64, len(c.COuts))
for i, cout := range c.COuts {
changeAmts[i] = cout.ChangeAmt
}
// Check and make sure none of the change overflows
// the input amounts.
for i, amt := range inputAmts {
if changeAmts[i] >= amt {
return nil, rpcInvalidError("input %v >= amount %v",
changeAmts[i], amt)
}
}
// Obtain the commitment amounts.
_, amountsCommitted, err := stake.SStxNullOutputAmounts(inputAmts,
changeAmts, amtTicket)
if err != nil {
return nil, rpcInternalError(err.Error(),
"Invalid SSTx output amounts")
}
for i, cout := range c.COuts {
// 1. Append future commitment output.
addr, err := dcrutil.DecodeAddress(cout.Addr,
activeNetParams.Params)
if err != nil {
return nil, rpcAddressKeyError("Could not decode "+
"address: %v", err)
}
// 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 *dcrutil.AddressPubKeyHash:
break
case *dcrutil.AddressScriptHash:
break
default:
return nil, rpcAddressKeyError("Invalid type: %T", addr)
}
if !addr.IsForNet(s.server.chainParams) {
return nil, rpcAddressKeyError("Wrong network: %v",
addr)
}
// Create an OP_RETURN push containing the pubkeyhash to send
// rewards to. TODO Replace 0x0000 fee limits with an argument
// passed to the RPC call.
pkScript, err := txscript.GenerateSStxAddrPush(addr,
dcrutil.Amount(amountsCommitted[i]), 0x0000)
if err != nil {
return nil, rpcInternalError(err.Error(),
"Could not create SStx script")
}
txout := wire.NewTxOut(int64(0), pkScript)
mtx.AddTxOut(txout)
// 2. Append change output.
// Ensure amount is in the valid range for monetary amounts.
if cout.ChangeAmt < 0 || cout.ChangeAmt > dcrutil.MaxAmount {
return nil, rpcInvalidError("Invalid change amount: 0 "+
"> %v > %v", cout.ChangeAmt, dcrutil.MaxAmount)
}
// Decode the provided address.
addr, err = dcrutil.DecodeAddress(cout.ChangeAddr,
activeNetParams.Params)
if err != nil {
return nil, rpcAddressKeyError("Wrong network: %v",
addr)
}
// 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 *dcrutil.AddressPubKeyHash:
break
case *dcrutil.AddressScriptHash:
break
default:
return nil, rpcAddressKeyError("Invalid type: %T", addr)
}
if !addr.IsForNet(s.server.chainParams) {
return nil, rpcAddressKeyError("Wrong network: %v",
addr)
}
// Create a new script which pays to the provided address with
// an SStx change tagged output.
pkScript, err = txscript.PayToSStxChange(addr)
if err != nil {
return nil, rpcInternalError(err.Error(),
"Could not create SStx change script")
}
txOut := wire.NewTxOut(cout.ChangeAmt, pkScript)
mtx.AddTxOut(txOut)
}
// Make sure we generated a valid SStx.
if _, err := stake.IsSStx(mtx); err != nil {
return nil, rpcInternalError(err.Error(),
"Invalid SStx")
}
// Return the serialized and hex-encoded transaction.
mtxHex, err := messageToHex(mtx)
if err != nil {
return nil, err
}
return mtxHex, nil
}
// handleCreateRawSSGenTx handles createrawssgentx commands.
func handleCreateRawSSGenTx(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
c := cmd.(*dcrjson.CreateRawSSGenTxCmd)
// Only a single SStx should be given
if len(c.Inputs) != 1 {
return nil, rpcInvalidError("SSGen Tx can only have one valid" +
" input")
}
// 1. Fetch the SStx, then calculate all the values we'll need later for
// the generation of the SSGen tx outputs.
//
// Convert the provided transaction hash hex to a chainhash.Hash.
txHash, err := chainhash.NewHashFromStr(c.Inputs[0].Txid)
if err != nil {
return nil, &dcrjson.RPCError{
Code: dcrjson.ErrRPCBlockNotFound,
Message: fmt.Sprintf("Inputs 0 Txid: %v", err),
}
}
// Try to fetch the ticket from the block database.
ticketUtx, err := s.chain.FetchUtxoEntry(txHash)
if err != nil {
rpcNoTxInfoError(txHash)
}
if t := ticketUtx.TransactionType(); t != stake.TxTypeSStx {
return nil, rpcDeserializationError("Invalid Tx type: %v", t)
}
// Store the sstx pubkeyhashes and amounts as found in the transaction
// outputs.
minimalOutputs := blockchain.ConvertUtxosToMinimalOutputs(ticketUtx)
ssgenPayTypes, ssgenPkhs, sstxAmts, _, _, _ :=
stake.SStxStakeOutputInfo(minimalOutputs)
// Get the current reward.
blockHash, curHeight := s.server.blockManager.chainState.Best()
stakeVoteSubsidy := blockchain.CalcStakeVoteSubsidy(
s.chain.FetchSubsidyCache(), curHeight, activeNetParams.Params)
// Calculate the output values from this data.
ssgenCalcAmts := stake.CalculateRewards(sstxAmts,
minimalOutputs[0].Value,
stakeVoteSubsidy)
// 2. Add all transaction inputs to a new transaction after performing
// some validity checks. First, add the stake base, then the OP_SSTX
// tagged output.
mtx := wire.NewMsgTx()
stakeBaseOutPoint := wire.NewOutPoint(&chainhash.Hash{},
uint32(0xFFFFFFFF), int8(0x01))
txInStakeBase := wire.NewTxIn(stakeBaseOutPoint, []byte{})
mtx.AddTxIn(txInStakeBase)
for _, input := range c.Inputs {
txHash, err := chainhash.NewHashFromStr(input.Txid)
if err != nil {
return nil, rpcDecodeHexError(input.Txid)
}
if input.Vout < 0 {
return nil, rpcInvalidError("Vout must be positive")
}
if !(input.Tree == wire.TxTreeStake) {
return nil, rpcInvalidError("Input tree is not " +
"TxTreeStake type")
}
prevOut := wire.NewOutPoint(txHash, input.Vout, input.Tree)
txIn := wire.NewTxIn(prevOut, []byte{})
mtx.AddTxIn(txIn)
}
// 3. Add the OP_RETURN null data pushes of the block header hash, the