forked from decred/dcrd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpcserver.go
5302 lines (4722 loc) · 164 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-2015 The btcsuite developers
// Copyright (c) 2015-2016 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/subtle"
"crypto/tls"
"encoding/base64"
"encoding/binary"
"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/fastsha256"
"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/txscript"
"github.com/decred/dcrd/wire"
"github.com/decred/dcrutil"
)
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"
)
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",
}
)
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,
"existsaddress": handleExistsAddress,
"existsaddresses": handleExistsAddresses,
"existsliveticket": handleExistsLiveTicket,
"existslivetickets": handleExistsLiveTickets,
"existsmempooltxs": handleExistsMempoolTxs,
"generate": handleGenerate,
"getaddednodeinfo": handleGetAddedNodeInfo,
"getbestblock": handleGetBestBlock,
"getbestblockhash": handleGetBestBlockHash,
"getblock": handleGetBlock,
"getblockcount": handleGetBlockCount,
"getblockhash": handleGetBlockHash,
"getblocktemplate": handleGetBlockTemplate,
"getcoinsupply": handleGetCoinSupply,
"getconnectioncount": handleGetConnectionCount,
"getcurrentnet": handleGetCurrentNet,
"getdifficulty": handleGetDifficulty,
"getgenerate": handleGetGenerate,
"gethashespersec": handleGetHashesPerSec,
"getinfo": handleGetInfo,
"getmininginfo": handleGetMiningInfo,
"getnettotals": handleGetNetTotals,
"getnetworkhashps": handleGetNetworkHashPS,
"getpeerinfo": handleGetPeerInfo,
"getrawmempool": handleGetRawMempool,
"getrawtransaction": handleGetRawTransaction,
"getstakedifficulty": handleGetStakeDifficulty,
"getticketpoolvalue": handleGetTicketPoolValue,
"gettxout": handleGetTxOut,
"getwork": handleGetWork,
"help": handleHelp,
"livetickets": handleLiveTickets,
"missedtickets": handleMissedTickets,
"node": handleNode,
"ping": handlePing,
"rebroadcastmissed": handleRebroadcastMissed,
"rebroadcastwinners": handleRebroadcastWinners,
"searchrawtransactions": handleSearchRawTransactions,
"sendrawtransaction": handleSendRawTransaction,
"setgenerate": handleSetGenerate,
"stop": handleStop,
"submitblock": handleSubmitBlock,
"ticketsforaddress": handleTicketsForAddress,
"validateaddress": handleValidateAddress,
"verifychain": handleVerifyChain,
"verifymessage": handleVerifyMessage,
}
// list of commands that we recognise, 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": struct{}{},
"accountfetchaddresses": struct{}{},
"accountsyncaddressindex": struct{}{},
"addmultisigaddress": struct{}{},
"backupwallet": struct{}{},
"createencryptedwallet": struct{}{},
"createmultisig": struct{}{},
"dumpprivkey": struct{}{},
"dumpwallet": struct{}{},
"encryptwallet": struct{}{},
"getaccount": struct{}{},
"getaccountaddress": struct{}{},
"getaddressesbyaccount": struct{}{},
"getbalance": struct{}{},
"getnewaddress": struct{}{},
"getrawchangeaddress": struct{}{},
"getreceivedbyaccount": struct{}{},
"getreceivedbyaddress": struct{}{},
"getstakeinfo": struct{}{},
"getticketvotebits": struct{}{},
"getticketsvotebits": struct{}{},
"gettransaction": struct{}{},
"gettxoutsetinfo": struct{}{},
"getunconfirmedbalance": struct{}{},
"getwalletinfo": struct{}{},
"importprivkey": struct{}{},
"importwallet": struct{}{},
"keypoolrefill": struct{}{},
"listaccounts": struct{}{},
"listaddressgroupings": struct{}{},
"listlockunspent": struct{}{},
"listreceivedbyaccount": struct{}{},
"listreceivedbyaddress": struct{}{},
"listsinceblock": struct{}{},
"listtransactions": struct{}{},
"listunspent": struct{}{},
"lockunspent": struct{}{},
"move": struct{}{},
"sendfrom": struct{}{},
"sendmany": struct{}{},
"sendtoaddress": struct{}{},
"setaccount": struct{}{},
"setticketvotebits": struct{}{},
"settxfee": struct{}{},
"signmessage": struct{}{},
"signrawtransaction": struct{}{},
"walletinfo": struct{}{},
"walletlock": struct{}{},
"walletpassphrase": struct{}{},
"walletpassphrasechange": struct{}{},
}
// Commands that are currently unimplemented, but should ultimately be.
var rpcUnimplemented = map[string]struct{}{
"estimatepriority": struct{}{},
"getblockchaininfo": struct{}{},
"getchaintips": struct{}{},
"getnetworkinfo": struct{}{},
}
// Commands that are available to a limited user
var rpcLimited = map[string]struct{}{
// Websockets commands
"notifyblocks": struct{}{},
"notifynewtransactions": struct{}{},
"notifyreceived": struct{}{},
"notifyspent": struct{}{},
"rescan": struct{}{},
// Websockets AND HTTP/S commands
"help": struct{}{},
// HTTP/S-only commands
"createrawtransaction": struct{}{},
"decoderawtransaction": struct{}{},
"decodescript": struct{}{},
"getbestblock": struct{}{},
"getbestblockhash": struct{}{},
"getblock": struct{}{},
"getblockcount": struct{}{},
"getblockhash": struct{}{},
"getcurrentnet": struct{}{},
"getdifficulty": struct{}{},
"getinfo": struct{}{},
"getnettotals": struct{}{},
"getnetworkhashps": struct{}{},
"getrawmempool": struct{}{},
"getrawtransaction": struct{}{},
"gettxout": struct{}{},
"searchrawtransactions": struct{}{},
"sendrawtransaction": struct{}{},
"submitblock": struct{}{},
"validateaddress": struct{}{},
"verifymessage": struct{}{},
}
// 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) *dcrjson.RPCError {
logStr := errStr
if context != "" {
logStr = context + ": " + errStr
}
rpcsLog.Error(logStr)
return dcrjson.NewRPCError(dcrjson.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) *dcrjson.RPCError {
return dcrjson.NewRPCError(dcrjson.ErrRPCDecodeHexString,
fmt.Sprintf("Argument must be hexadecimal string (not %q)",
gotHex))
}
// 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, &dcrjson.RPCError{
Code: dcrjson.ErrRPCInvalidParameter,
Message: "invalid subcommand for addnode",
}
}
if err != nil {
return nil, &dcrjson.RPCError{
Code: dcrjson.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.(*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, &dcrjson.RPCError{
Code: dcrjson.ErrRPCInvalidParameter,
Message: "invalid address or node ID",
}
}
}
if err != nil && peerExists(s.server.PeerInfo(), addr, int32(nodeId)) {
return nil, &dcrjson.RPCError{
Code: dcrjson.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.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, &dcrjson.RPCError{
Code: dcrjson.ErrRPCInvalidParameter,
Message: "invalid address or node ID",
}
}
}
if err != nil && peerExists(s.server.PeerInfo(), addr, int32(nodeId)) {
return nil, &dcrjson.RPCError{
Code: dcrjson.ErrRPCMisc,
Message: "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, &dcrjson.RPCError{
Code: dcrjson.ErrRPCInvalidParameter,
Message: "invalid subcommand for node connect",
}
}
default:
return nil, &dcrjson.RPCError{
Code: dcrjson.ErrRPCInvalidParameter,
Message: "invalid subcommand for node",
}
}
if err != nil {
return nil, &dcrjson.RPCError{
Code: dcrjson.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(peerInfos []*dcrjson.GetPeerInfoResult, addr string, nodeId int32) bool {
for _, peerInfo := range peerInfos {
if peerInfo.ID == nodeId || peerInfo.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 "", 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.(*dcrjson.CreateRawTransactionCmd)
// 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 !(int8(input.Tree) == dcrutil.TxTreeRegular ||
int8(input.Tree) == dcrutil.TxTreeStake) {
return nil, dcrjson.RPCError{
Code: dcrjson.ErrRPCInvalidParams.Code,
Message: "Invalid parameter, tx tree must be regular or stake",
}
}
prevOut := wire.NewOutPoint(txHash, uint32(input.Vout), int8(input.Tree))
txIn := wire.NewTxIn(prevOut, []byte{})
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, dcrjson.RPCError{
Code: dcrjson.ErrRPCType,
Message: "Invalid amount",
}
}
// Decode the provided address.
addr, err := dcrutil.DecodeAddress(encodedAddr,
activeNetParams.Params)
if err != nil {
return nil, dcrjson.RPCError{
Code: dcrjson.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 *dcrutil.AddressPubKeyHash:
case *dcrutil.AddressScriptHash:
default:
return nil, &dcrjson.RPCError{
Code: dcrjson.ErrRPCInvalidAddressOrKey,
Message: "Invalid address or key",
}
}
if !addr.IsForNet(s.server.chainParams) {
return nil, dcrjson.RPCError{
Code: dcrjson.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 {
return nil, dcrjson.RPCError{
Code: dcrjson.ErrRPCInternal.Code,
Message: err.Error(),
}
}
atomic, err := dcrutil.NewAmount(amount)
if err != nil {
return nil, dcrjson.RPCError{
Code: dcrjson.ErrRPCInternal.Code,
Message: err.Error(),
}
}
txOut := wire.NewTxOut(int64(atomic), pkScript)
mtx.AddTxOut(txOut)
}
// Return the serialized and hex-encoded transaction.
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) {
errStr := fmt.Sprintf("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))
return nil, errors.New(errStr)
}
if len(c.Amount) != 1 {
errStr := fmt.Sprintf("Only one SSGen tagged output is allowed "+
"per sstx; len ssgenout %v", len(c.Amount))
return nil, errors.New(errStr)
}
// 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, dcrjson.RPCError{
Code: dcrjson.ErrRPCInvalidParameter,
Message: "Invalid parameter, vout must be positive",
}
}
if !(int8(input.Tree) == dcrutil.TxTreeRegular ||
int8(input.Tree) == dcrutil.TxTreeStake) {
return nil, dcrjson.RPCError{
Code: dcrjson.ErrRPCInvalidParameter,
Message: "Invalid parameter, tx tree must be regular or stake",
}
}
prevOut := wire.NewOutPoint(txHash, uint32(input.Vout), int8(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 {
errStr := fmt.Sprintf("Invalid sstx commitment amount %v", amount)
return nil, dcrjson.RPCError{
Code: dcrjson.ErrRPCType,
Message: errStr,
}
}
// Decode the provided address.
addr, err := dcrutil.DecodeAddress(encodedAddr,
activeNetParams.Params)
if err != nil {
return nil, dcrjson.RPCError{
Code: dcrjson.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 *dcrutil.AddressPubKeyHash:
default:
return nil, &dcrjson.RPCError{
Code: dcrjson.ErrRPCInvalidAddressOrKey,
Message: "Invalid address or key",
}
}
if !addr.IsForNet(s.server.chainParams) {
return nil, dcrjson.RPCError{
Code: dcrjson.ErrRPCInvalidAddressOrKey,
Message: "Invalid address: " + encodedAddr +
" is for the wrong network",
}
}
// 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, dcrjson.RPCError{
Code: dcrjson.ErrRPCInternal.Code,
Message: err.Error(),
}
}
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 {
errStr := fmt.Sprintf("Invalid sstx change amount %v; "+
"should have been less than input amt of %v",
changeAmts[i], amt)
return nil, dcrjson.RPCError{
Code: dcrjson.ErrRPCType,
Message: errStr,
}
}
}
// Obtain the commitment amounts.
_, amountsCommitted, err := stake.GetSStxNullOutputAmounts(inputAmts,
changeAmts, amtTicket)
if err != nil {
return nil, err
}
for i, cout := range c.COuts {
// 1. Append future commitment output.
addr, err := dcrutil.DecodeAddress(cout.Addr,
activeNetParams.Params)
if err != nil {
return nil, fmt.Errorf("cannot decode address: %s", 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, &dcrjson.RPCError{
Code: dcrjson.ErrRPCInvalidAddressOrKey,
Message: "Invalid address or key",
}
}
if !addr.IsForNet(s.server.chainParams) {
return nil, dcrjson.RPCError{
Code: dcrjson.ErrRPCInvalidAddressOrKey,
Message: "Invalid address: " +
" is for the wrong network",
}
}
// 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, fmt.Errorf("cannot create txout script: %s", err)
}
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 {
errStr := fmt.Sprintf("Invalid sstx change amount %v",
cout.ChangeAmt)
return nil, dcrjson.RPCError{
Code: dcrjson.ErrRPCType,
Message: errStr,
}
}
// Decode the provided address.
addr, err = dcrutil.DecodeAddress(cout.ChangeAddr,
activeNetParams.Params)
if err != nil {
return nil, dcrjson.RPCError{
Code: dcrjson.ErrRPCInvalidAddressOrKey,
Message: "Invalid address: " +
" is for the wrong network",
}
}
// 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, &dcrjson.RPCError{
Code: dcrjson.ErrRPCInvalidAddressOrKey,
Message: "Invalid address or key",
}
}
if !addr.IsForNet(s.server.chainParams) {
return nil, dcrjson.RPCError{
Code: dcrjson.ErrRPCInvalidAddressOrKey,
Message: fmt.Sprintf("%s: %q",
"Wront network",
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, dcrjson.RPCError{
Code: dcrjson.ErrRPCInternal.Code,
Message: err.Error(),
}
}
txOut := wire.NewTxOut(cout.ChangeAmt, pkScript)
mtx.AddTxOut(txOut)
}
// Make sure we generated a valid SStx.
if _, err := stake.IsSStx(dcrutil.NewTx(mtx)); err != nil {
return nil, err
}
// 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, dcrjson.RPCError{
Code: dcrjson.ErrRPCInvalidParameter,
Message: "Invalid parameter, SSGen tx 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 ShaHash.
txSha, err := chainhash.NewHashFromStr(c.Inputs[0].Txid)
if err != nil {
rpcsLog.Errorf("Error generating sha: %v", err)
return nil, dcrjson.RPCError{
Code: dcrjson.ErrRPCBlockNotFound,
Message: "c.Inputs[0].Txid must be a hexadecimal string",
}
}
// Try to fetch the transaction from the memory pool and if that fails,
// try the block database.
var sstxmtx *wire.MsgTx
tx, err := s.server.txMemPool.FetchTransaction(txSha)
if err != nil {
txList, err := s.server.db.FetchTxBySha(txSha)
if err != nil {
rpcsLog.Errorf("Error fetching tx: %v", err)
return nil, &dcrjson.RPCError{
Code: dcrjson.ErrRPCNoTxInfo,
Message: "No information available about transaction",
}
}
if len(txList) == 0 {
return nil, &dcrjson.RPCError{
Code: dcrjson.ErrRPCNoTxInfo,
Message: "No information available about transaction",
}
}
lastTx := len(txList) - 1
sstxmtx = txList[lastTx].Tx
} else {
sstxmtx = tx.MsgTx()
}
// Store the sstx pubkeyhashes and amounts as found in the transaction
// outputs.
sstx := dcrutil.NewTx(sstxmtx)
ssgenPayTypes, ssgenPkhs, sstxAmts, _, _, _ :=
stake.GetSStxStakeOutputInfo(sstx)
// Get the current reward.
blockSha, curHeight := s.server.blockManager.chainState.Best()
stakeVoteSubsidy := blockchain.CalcStakeVoteSubsidy(curHeight,
activeNetParams.Params)
// Calculate the output values from this data.
ssgenCalcAmts := stake.GetStakeRewards(sstxAmts,
sstxmtx.TxOut[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, dcrjson.NewRPCError(dcrjson.ErrRPCDecodeHexString,
fmt.Sprintf("Argument must be hexadecimal string (not %q)",
txHash))
}
if input.Vout < 0 {
return nil, dcrjson.RPCError{
Code: dcrjson.ErrRPCInvalidParameter,
Message: "Invalid parameter, vout must be positive",
}
}
if !(int8(input.Tree) == dcrutil.TxTreeStake) {
return nil, dcrjson.RPCError{
Code: dcrjson.ErrRPCInvalidParameter,
Message: "Invalid parameter, tx tree of sstx input must be stake",
}
}
prevOut := wire.NewOutPoint(txHash, uint32(input.Vout), int8(input.Tree))