-
-
Notifications
You must be signed in to change notification settings - Fork 635
/
decredrpc.go
885 lines (752 loc) · 25.3 KB
/
decredrpc.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
package dcr
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math/big"
"net"
"net/http"
"runtime/debug"
"strconv"
"strings"
"sync"
"time"
"github.com/decred/dcrd/dcrjson/v3"
"github.com/golang/glog"
"github.com/juju/errors"
"github.com/trezor/blockbook/bchain"
"github.com/trezor/blockbook/bchain/coins/btc"
"github.com/trezor/blockbook/common"
)
// voteBitYes defines the vote bit set when a given block validates the previous
// block
const voteBitYes = 0x0001
type DecredRPC struct {
*btc.BitcoinRPC
mtx sync.Mutex
client http.Client
rpcURL string
rpcUser string
bestBlock uint32
rpcPassword string
}
// NewDecredRPC returns new DecredRPC instance.
func NewDecredRPC(config json.RawMessage, pushHandler func(bchain.NotificationType)) (bchain.BlockChain, error) {
b, err := btc.NewBitcoinRPC(config, pushHandler)
if err != nil {
return nil, err
}
var c btc.Configuration
if err = json.Unmarshal(config, &c); err != nil {
return nil, errors.Annotate(err, "Invalid configuration file")
}
transport := &http.Transport{
Dial: (&net.Dialer{KeepAlive: 600 * time.Second}).Dial,
MaxIdleConns: 100,
MaxIdleConnsPerHost: 100, // necessary to not to deplete ports
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
d := &DecredRPC{
BitcoinRPC: b.(*btc.BitcoinRPC),
client: http.Client{Timeout: time.Duration(c.RPCTimeout) * time.Second, Transport: transport},
rpcURL: c.RPCURL,
rpcUser: c.RPCUser,
rpcPassword: c.RPCPass,
}
d.BitcoinRPC.RPCMarshaler = btc.JSONMarshalerV1{}
d.BitcoinRPC.ChainConfig.SupportsEstimateSmartFee = false
return d, nil
}
// Initialize initializes DecredRPC instance.
func (d *DecredRPC) Initialize() error {
chainInfo, err := d.GetChainInfo()
if err != nil {
return err
}
chainName := chainInfo.Chain
glog.Info("Chain name ", chainName)
params := GetChainParams(chainName)
// always create parser
d.BitcoinRPC.Parser = NewDecredParser(params, d.BitcoinRPC.ChainConfig)
// parameters for getInfo request
if params.Net == MainnetMagic {
d.BitcoinRPC.Testnet = false
d.BitcoinRPC.Network = "livenet"
} else {
d.BitcoinRPC.Testnet = true
d.BitcoinRPC.Network = "testnet"
}
glog.Info("rpc: block chain ", params.Name)
return nil
}
type Error struct {
Code int `json:"code"`
Message string `json:"message"`
}
type GenericCmd struct {
ID int `json:"id"`
Method string `json:"method"`
Params []interface{} `json:"params,omitempty"`
}
type GetBlockChainInfoResult struct {
Error Error `json:"error"`
Result struct {
Chain string `json:"chain"`
Blocks int64 `json:"blocks"`
Headers int64 `json:"headers"`
SyncHeight int64 `json:"syncheight"`
BestBlockHash string `json:"bestblockhash"`
Difficulty uint32 `json:"difficulty"`
VerificationProgress float64 `json:"verificationprogress"`
ChainWork string `json:"chainwork"`
InitialBlockDownload bool `json:"initialblockdownload"`
MaxBlockSize int64 `json:"maxblocksize"`
} `json:"result"`
}
type GetNetworkInfoResult struct {
Error Error `json:"error"`
Result struct {
Version int32 `json:"version"`
ProtocolVersion int32 `json:"protocolversion"`
TimeOffset int64 `json:"timeoffset"`
Connections int32 `json:"connections"`
RelayFee float64 `json:"relayfee"`
} `json:"result"`
}
type GetInfoChainResult struct {
Error Error `json:"error"`
Result struct {
Version int32 `json:"version"`
ProtocolVersion int32 `json:"protocolversion"`
Blocks int64 `json:"blocks"`
TimeOffset int64 `json:"timeoffset"`
Connections int32 `json:"connections"`
Proxy string `json:"proxy"`
Difficulty float64 `json:"difficulty"`
TestNet bool `json:"testnet"`
RelayFee float64 `json:"relayfee"`
Errors string `json:"errors"`
}
}
type GetBestBlockResult struct {
Error Error `json:"error"`
Result struct {
Hash string `json:"hash"`
Height uint32 `json:"height"`
} `json:"result"`
}
type GetBlockHashResult struct {
Error Error `json:"error"`
Result string `json:"result"`
}
type GetBlockResult struct {
Error Error `json:"error"`
Result struct {
Hash string `json:"hash"`
Confirmations int64 `json:"confirmations"`
Size int32 `json:"size"`
Height uint32 `json:"height"`
Version common.JSONNumber `json:"version"`
MerkleRoot string `json:"merkleroot"`
StakeRoot string `json:"stakeroot"`
RawTx []RawTx `json:"rawtx"`
Tx []string `json:"tx,omitempty"`
STx []string `json:"stx,omitempty"`
Time int64 `json:"time"`
Nonce common.JSONNumber `json:"nonce"`
VoteBits uint16 `json:"votebits"`
FinalState string `json:"finalstate"`
Voters uint16 `json:"voters"`
FreshStake uint8 `json:"freshstake"`
Revocations uint8 `json:"revocations"`
PoolSize uint32 `json:"poolsize"`
Bits string `json:"bits"`
SBits float64 `json:"sbits"`
ExtraData string `json:"extradata"`
StakeVersion uint32 `json:"stakeversion"`
Difficulty float64 `json:"difficulty"`
ChainWork string `json:"chainwork"`
PreviousHash string `json:"previousblockhash"`
NextHash string `json:"nextblockhash,omitempty"`
} `json:"result"`
}
type GetBlockHeaderResult struct {
Error Error `json:"error"`
Result struct {
Hash string `json:"hash"`
Confirmations int64 `json:"confirmations"`
Version common.JSONNumber `json:"version"`
MerkleRoot string `json:"merkleroot"`
StakeRoot string `json:"stakeroot"`
VoteBits uint16 `json:"votebits"`
FinalState string `json:"finalstate"`
Voters uint16 `json:"voters"`
FreshStake uint8 `json:"freshstake"`
Revocations uint8 `json:"revocations"`
PoolSize uint32 `json:"poolsize"`
Bits string `json:"bits"`
SBits float64 `json:"sbits"`
Height uint32 `json:"height"`
Size uint32 `json:"size"`
Time int64 `json:"time"`
Nonce uint32 `json:"nonce"`
ExtraData string `json:"extradata"`
StakeVersion uint32 `json:"stakeversion"`
Difficulty float64 `json:"difficulty"`
ChainWork string `json:"chainwork"`
PreviousHash string `json:"previousblockhash,omitempty"`
NextHash string `json:"nextblockhash,omitempty"`
} `json:"result"`
}
type ScriptSig struct {
Asm string `json:"asm"`
Hex string `json:"hex"`
}
type Vin struct {
Coinbase string `json:"coinbase"`
Stakebase string `json:"stakebase"`
Txid string `json:"txid"`
Vout uint32 `json:"vout"`
Tree int8 `json:"tree"`
Sequence uint32 `json:"sequence"`
AmountIn float64 `json:"amountin"`
BlockHeight uint32 `json:"blockheight"`
BlockIndex uint32 `json:"blockindex"`
ScriptSig *ScriptSig `json:"scriptsig"`
}
type ScriptPubKeyResult struct {
Asm string `json:"asm"`
Hex string `json:"hex,omitempty"`
ReqSigs int32 `json:"reqSigs,omitempty"`
Type string `json:"type"`
Addresses []string `json:"addresses,omitempty"`
CommitAmt *float64 `json:"commitamt,omitempty"`
}
type Vout struct {
Value float64 `json:"value"`
N uint32 `json:"n"`
Version uint16 `json:"version"`
ScriptPubKey ScriptPubKeyResult `json:"scriptPubKey"`
}
type RawTx struct {
Hex string `json:"hex"`
Txid string `json:"txid"`
Version int32 `json:"version"`
LockTime uint32 `json:"locktime"`
Vin []Vin `json:"vin"`
Vout []Vout `json:"vout"`
Expiry uint32 `json:"expiry"`
BlockIndex uint32 `json:"blockindex,omitempty"`
Confirmations int64 `json:"confirmations,omitempty"`
Time int64 `json:"time,omitempty"`
Blocktime int64 `json:"blocktime,omitempty"`
TxExtraInfo
}
type GetTransactionResult struct {
Error Error `json:"error"`
Result struct {
RawTx
} `json:"result"`
}
type MempoolTxsResult struct {
Error Error `json:"error"`
Result []string `json:"result"`
}
type EstimateSmartFeeResult struct {
Error Error `json:"error"`
Result struct {
FeeRate float64 `json:"feerate"`
Errors []string `json:"errors"`
Blocks int64 `json:"blocks"`
} `json:"result"`
}
type EstimateFeeResult struct {
Error Error `json:"error"`
Result common.JSONNumber `json:"result"`
}
type SendRawTransactionResult struct {
Error Error `json:"error"`
Result string `json:"result"`
}
type DecodeRawTransactionResult struct {
Error Error `json:"error"`
Result struct {
Txid string `json:"txid"`
Version int32 `json:"version"`
Locktime uint32 `json:"locktime"`
Expiry uint32 `json:"expiry"`
Vin []Vin `json:"vin"`
Vout []Vout `json:"vout"`
TxExtraInfo
} `json:"result"`
}
type TxExtraInfo struct {
BlockHeight uint32 `json:"blockheight,omitempty"`
BlockHash string `json:"blockhash,omitempty"`
}
func (d *DecredRPC) GetChainInfo() (*bchain.ChainInfo, error) {
blockchainInfoRequest := GenericCmd{
ID: 1,
Method: "getblockchaininfo",
}
var blockchainInfoResult GetBlockChainInfoResult
if err := d.Call(blockchainInfoRequest, &blockchainInfoResult); err != nil {
return nil, err
}
if blockchainInfoResult.Error.Message != "" {
return nil, mapToStandardErr("Error fetching blockchain info: %s", blockchainInfoResult.Error)
}
infoChainRequest := GenericCmd{
ID: 2,
Method: "getinfo",
}
var infoChainResult GetInfoChainResult
if err := d.Call(infoChainRequest, &infoChainResult); err != nil {
return nil, err
}
if infoChainResult.Error.Message != "" {
return nil, mapToStandardErr("Error fetching network info: %s", infoChainResult.Error)
}
chainInfo := &bchain.ChainInfo{
Chain: blockchainInfoResult.Result.Chain,
Blocks: int(blockchainInfoResult.Result.Blocks),
Headers: int(blockchainInfoResult.Result.Headers),
Bestblockhash: blockchainInfoResult.Result.BestBlockHash,
Difficulty: strconv.Itoa(int(blockchainInfoResult.Result.Difficulty)),
SizeOnDisk: blockchainInfoResult.Result.SyncHeight,
Version: strconv.Itoa(int(infoChainResult.Result.Version)),
Subversion: "",
ProtocolVersion: strconv.Itoa(int(infoChainResult.Result.ProtocolVersion)),
Timeoffset: float64(infoChainResult.Result.TimeOffset),
Warnings: "",
}
return chainInfo, nil
}
// getChainBestBlock returns the best block according to dcrd chain. This block
// has no atleast one confirming block.
func (d *DecredRPC) getChainBestBlock() (*GetBestBlockResult, error) {
bestBlockRequest := GenericCmd{
ID: 1,
Method: "getbestblock",
}
var bestBlockResult GetBestBlockResult
if err := d.Call(bestBlockRequest, &bestBlockResult); err != nil {
return nil, err
}
if bestBlockResult.Error.Message != "" {
return nil, mapToStandardErr("Error fetching best block: %s", bestBlockResult.Error)
}
return &bestBlockResult, nil
}
// getBestBlock returns details for the block mined immediately before the
// official dcrd chain's bestblock i.e. it has a minimum of 1 confirmation.
// The chain's best block is not returned as its block validity is not guarranteed.
func (d *DecredRPC) getBestBlock() (*GetBestBlockResult, error) {
bestBlockResult, err := d.getChainBestBlock()
if err != nil {
return nil, err
}
// remove the block with less than 1 confirming block
bestBlockResult.Result.Height--
validBlockHash, err := d.getBlockHashByHeight(bestBlockResult.Result.Height)
if err != nil {
return nil, err
}
bestBlockResult.Result.Hash = validBlockHash.Result
return bestBlockResult, nil
}
// GetBestBlockHash returns the block hash of the most recent block to be mined
// and has a minimum of 1 confirming block.
func (d *DecredRPC) GetBestBlockHash() (string, error) {
bestBlock, err := d.getBestBlock()
if err != nil {
return "", err
}
return bestBlock.Result.Hash, nil
}
// GetBestBlockHeight returns the block height of the most recent block to be mined
// and has a minimum of 1 confirming block.
func (d *DecredRPC) GetBestBlockHeight() (uint32, error) {
bestBlock, err := d.getBestBlock()
if err != nil {
return 0, err
}
return uint32(bestBlock.Result.Height), err
}
// GetBlockHash returns the block hash of the block at the provided height.
func (d *DecredRPC) GetBlockHash(height uint32) (string, error) {
blockHashResult, err := d.getBlockHashByHeight(height)
if err != nil {
return "", err
}
return blockHashResult.Result, nil
}
func (d *DecredRPC) getBlockHashByHeight(height uint32) (*GetBlockHashResult, error) {
blockHashRequest := GenericCmd{
ID: 1,
Method: "getblockhash",
Params: []interface{}{height},
}
var blockHashResult GetBlockHashResult
if err := d.Call(blockHashRequest, &blockHashResult); err != nil {
return nil, err
}
if blockHashResult.Error.Message != "" {
return nil, mapToStandardErr("Error fetching block hash: %s", blockHashResult.Error)
}
return &blockHashResult, nil
}
// GetBlockHeader returns the block header of the block the provided block hash.
func (d *DecredRPC) GetBlockHeader(hash string) (*bchain.BlockHeader, error) {
blockHeaderRequest := GenericCmd{
ID: 1,
Method: "getblockheader",
Params: []interface{}{hash},
}
var blockHeader GetBlockHeaderResult
if err := d.Call(blockHeaderRequest, &blockHeader); err != nil {
return nil, err
}
if blockHeader.Error.Message != "" {
return nil, mapToStandardErr("Error fetching block info: %s", blockHeader.Error)
}
header := &bchain.BlockHeader{
Hash: blockHeader.Result.Hash,
Prev: blockHeader.Result.PreviousHash,
Next: blockHeader.Result.NextHash,
Height: blockHeader.Result.Height,
Confirmations: int(blockHeader.Result.Confirmations),
Size: int(blockHeader.Result.Size),
Time: blockHeader.Result.Time,
}
return header, nil
}
// GetBlock returns the block retrieved using the provided block hash by default
// or using the block height if an empty hash string was provided. If the
// requested block has less than 2 confirmation bchain.ErrBlockNotFound error
// is returned. This rule is in places to guarrantee that only validated block
// details (txs) are saved to the db. Access to the bestBlock height is threadsafe.
func (d *DecredRPC) GetBlock(hash string, height uint32) (*bchain.Block, error) {
// Confirm if the block at provided height has at least 2 confirming blocks.
d.mtx.Lock()
if height > d.bestBlock {
bestBlock, err := d.getBestBlock()
if err != nil || height > bestBlock.Result.Height {
// If an error occurred or the current height doesn't have a minimum
// of two confirming blocks (greater than best block), quit.
d.mtx.Unlock()
return nil, bchain.ErrBlockNotFound
}
d.bestBlock = bestBlock.Result.Height
}
d.mtx.Unlock() // Releases the lock soonest possible
if hash == "" {
getHashResult, err := d.getBlockHashByHeight(height)
if err != nil {
return nil, err
}
hash = getHashResult.Result
}
block, err := d.getBlock(hash)
if err != nil {
return nil, err
}
header := bchain.BlockHeader{
Hash: block.Result.Hash,
Prev: block.Result.PreviousHash,
Next: block.Result.NextHash,
Height: block.Result.Height,
Confirmations: int(block.Result.Confirmations),
Size: int(block.Result.Size),
Time: block.Result.Time,
}
bchainBlock := &bchain.Block{BlockHeader: header}
// Check the current block validity by fetch the next block
nextBlockHashResult, err := d.getBlockHashByHeight(height + 1)
if err != nil {
return nil, err
}
nextBlock, err := d.getBlock(nextBlockHashResult.Result)
if err != nil {
return nil, err
}
// If the Votesbits set equals to voteBitYes append the regular transactions.
if nextBlock.Result.VoteBits == voteBitYes {
for _, txID := range block.Result.Tx {
if block.Result.Height == 0 {
continue
}
tx, err := d.GetTransaction(txID)
if err != nil {
return nil, err
}
bchainBlock.Txs = append(bchainBlock.Txs, *tx)
}
}
return bchainBlock, nil
}
func (d *DecredRPC) getBlock(hash string) (*GetBlockResult, error) {
blockRequest := GenericCmd{
ID: 1,
Method: "getblock",
Params: []interface{}{hash},
}
var block GetBlockResult
//Need for skip block height 0 without data
if hash == "298e5cc3d985bfe7f81dc135f360abe089edd4396b86d2de66b0cef42b21d980" {
glog.Info("Skip 0 block with hash " + hash)
return &block, nil
}
if err := d.Call(blockRequest, &block); err != nil {
return nil, err
}
if block.Error.Message != "" {
return nil, mapToStandardErr("Error fetching block info: %s", block.Error)
}
return &block, nil
}
func (d *DecredRPC) decodeRawTransaction(txHex string) (*bchain.Tx, error) {
decodeRawTxRequest := GenericCmd{
ID: 1,
Method: "decoderawtransaction",
Params: []interface{}{txHex},
}
var decodeRawTxResult DecodeRawTransactionResult
if err := d.Call(decodeRawTxRequest, &decodeRawTxResult); err != nil {
return nil, err
}
if decodeRawTxResult.Error.Message != "" {
return nil, mapToStandardErr("Error decoding raw tx: %s", decodeRawTxResult.Error)
}
tx := &bchain.Tx{
Hex: txHex,
Txid: decodeRawTxResult.Result.Txid,
Version: decodeRawTxResult.Result.Version,
LockTime: decodeRawTxResult.Result.Locktime,
}
// Add block height and block hash info
tx.CoinSpecificData = decodeRawTxResult.Result.TxExtraInfo
return tx, nil
}
func (d *DecredRPC) GetBlockInfo(hash string) (*bchain.BlockInfo, error) {
block, err := d.getBlock(hash)
if err != nil {
return nil, err
}
header := bchain.BlockHeader{
Hash: block.Result.Hash,
Prev: block.Result.PreviousHash,
Next: block.Result.NextHash,
Height: block.Result.Height,
Confirmations: int(block.Result.Confirmations),
Size: int(block.Result.Size),
Time: int64(block.Result.Time),
}
bInfo := &bchain.BlockInfo{
BlockHeader: header,
MerkleRoot: block.Result.MerkleRoot,
Version: block.Result.Version,
Nonce: block.Result.Nonce,
Bits: block.Result.Bits,
Difficulty: common.JSONNumber(strconv.FormatFloat(block.Result.Difficulty, 'e', -1, 64)),
Txids: block.Result.Tx,
}
return bInfo, nil
}
// GetTransaction returns a transaction by the transaction ID
func (d *DecredRPC) GetTransaction(txid string) (*bchain.Tx, error) {
r, err := d.getRawTransaction(txid)
if err != nil {
return nil, err
}
tx, err := d.Parser.ParseTxFromJson(r)
if err != nil {
return nil, errors.Annotatef(err, "txid %v", txid)
}
return tx, nil
}
// getRawTransaction returns json as returned by backend, with all coin specific data
func (d *DecredRPC) getRawTransaction(txid string) (json.RawMessage, error) {
if txid == "" {
return nil, bchain.ErrTxidMissing
}
verbose := 1
getTxRequest := GenericCmd{
ID: 1,
Method: "getrawtransaction",
Params: []interface{}{txid, &verbose},
}
var getTxResult GetTransactionResult
if err := d.Call(getTxRequest, &getTxResult); err != nil {
return nil, err
}
if getTxResult.Error.Message != "" {
return nil, mapToStandardErr("Error fetching transaction: %s", getTxResult.Error)
}
bytes, err := json.Marshal(getTxResult.Result)
if err != nil {
return nil, errors.Annotatef(err, "txid %v", txid)
}
return json.RawMessage(bytes), nil
}
// GetTransactionForMempool returns the full tx information identified by the
// provided txid.
func (d *DecredRPC) GetTransactionForMempool(txid string) (*bchain.Tx, error) {
return d.GetTransaction(txid)
}
// GetMempoolTransactions returns a slice of regular transactions currently in
// the mempool. The block whose validation is still undecided will have its txs,
// listed like they are still in the mempool till the block is confirmed.
func (d *DecredRPC) GetMempoolTransactions() ([]string, error) {
verbose := false
txType := "regular"
mempoolRequest := GenericCmd{
ID: 1,
Method: "getrawmempool",
Params: []interface{}{&verbose, &txType},
}
var mempool MempoolTxsResult
if err := d.Call(mempoolRequest, &mempool); err != nil {
return []string{}, err
}
if mempool.Error.Message != "" {
return nil, mapToStandardErr("Error fetching mempool data: %s", mempool.Error)
}
unvalidatedBlockResult, err := d.getChainBestBlock()
if err != nil {
return nil, err
}
unvalidatedBlock, err := d.getBlock(unvalidatedBlockResult.Result.Hash)
if err != nil {
return nil, err
}
mempool.Result = append(mempool.Result, unvalidatedBlock.Result.Tx...)
return mempool.Result, nil
}
// GetTransactionSpecific returns the json raw message for the tx identified by
// the provided txid.
func (d *DecredRPC) GetTransactionSpecific(tx *bchain.Tx) (json.RawMessage, error) {
return d.getRawTransaction(tx.Txid)
}
// EstimateSmartFee returns fee estimation
func (d *DecredRPC) EstimateSmartFee(blocks int, conservative bool) (big.Int, error) {
estimateSmartFeeRequest := GenericCmd{
ID: 1,
Method: "estimatesmartfee",
Params: []interface{}{blocks},
}
var smartFeeEstimate EstimateSmartFeeResult
if err := d.Call(estimateSmartFeeRequest, &smartFeeEstimate); err != nil {
return *big.NewInt(0), err
}
if smartFeeEstimate.Error.Message != "" {
return *big.NewInt(0), mapToStandardErr("Error fetching smart fee estimate: %s", smartFeeEstimate.Error)
}
return *big.NewInt(int64(smartFeeEstimate.Result.FeeRate)), nil
}
// EstimateFee returns fee estimation.
func (d *DecredRPC) EstimateFee(blocks int) (big.Int, error) {
estimateFeeRequest := GenericCmd{
ID: 1,
Method: "estimatefee",
Params: []interface{}{blocks},
}
var feeEstimate EstimateFeeResult
if err := d.Call(estimateFeeRequest, &feeEstimate); err != nil {
return *big.NewInt(0), err
}
if feeEstimate.Error.Message != "" {
return *big.NewInt(0), mapToStandardErr("Error fetching fee estimate: %s", feeEstimate.Error)
}
r, err := d.Parser.AmountToBigInt(feeEstimate.Result)
if err != nil {
return r, err
}
return r, nil
}
func (d *DecredRPC) SendRawTransaction(tx string) (string, error) {
sendRawTxRequest := &GenericCmd{
ID: 1,
Method: "sendrawtransaction",
Params: []interface{}{tx},
}
var sendRawTxResult SendRawTransactionResult
err := d.Call(sendRawTxRequest, &sendRawTxResult)
if err != nil {
return "", err
}
if sendRawTxResult.Error.Message != "" {
return "", mapToStandardErr("error sending raw transaction: %s", sendRawTxResult.Error)
}
return sendRawTxResult.Result, nil
}
// Call calls Backend RPC interface, using RPCMarshaler interface to marshall the request
func (d *DecredRPC) Call(req interface{}, res interface{}) error {
httpData, err := json.Marshal(req)
if err != nil {
return err
}
httpReq, err := http.NewRequest("POST", d.rpcURL, bytes.NewBuffer(httpData))
if err != nil {
return err
}
httpReq.SetBasicAuth(d.rpcUser, d.rpcPassword)
httpRes, err := d.client.Do(httpReq)
// in some cases the httpRes can contain data even if it returns error
// see http://devs.cloudimmunity.com/gotchas-and-common-mistakes-in-go-golang/
if httpRes != nil {
defer httpRes.Body.Close()
}
if err != nil {
return err
}
// if server returns HTTP error code it might not return json with response
// handle both cases
if httpRes.StatusCode != 200 {
if err = safeDecodeResponse(httpRes.Body, &res); err != nil {
return errors.Errorf("%v %v", httpRes.Status, err)
}
return nil
}
return safeDecodeResponse(httpRes.Body, &res)
}
func safeDecodeResponse(body io.ReadCloser, res *interface{}) (err error) {
var data []byte
defer func() {
if r := recover(); r != nil {
glog.Error("unmarshal json recovered from panic: ", r, "; data: ", string(data))
debug.PrintStack()
if len(data) > 0 && len(data) < 2048 {
err = errors.Errorf("Error: %v", string(data))
} else {
err = errors.New("Internal error")
}
}
}()
data, err = ioutil.ReadAll(body)
if err != nil {
return err
}
error := json.Unmarshal(data, res)
return error
}
// mapToStandardErr map the dcrd API Message errors to the standard error messages
// supported by trezor. Dcrd errors to be mapped are listed here:
// https://github.com/decred/dcrd/blob/2f5e47371263b996bb99e8dc3484f659309bd83a/dcrjson/jsonerr.go
func mapToStandardErr(customPrefix string, err Error) error {
switch {
case strings.Contains(err.Message, dcrjson.ErrBlockNotFound.Message) || // Block not found
strings.Contains(err.Message, dcrjson.ErrOutOfRange.Message) || // Block number out of range
strings.Contains(err.Message, dcrjson.ErrBestBlockHash.Message): // Error getting best block hash
return bchain.ErrBlockNotFound
case strings.Contains(err.Message, dcrjson.ErrNoTxInfo.Message): // No information available about transaction
return bchain.ErrTxNotFound
case strings.Contains(err.Message, dcrjson.ErrInvalidTxVout.Message): // Output index number (vout) does not exist for transaction
return bchain.ErrTxidMissing
default:
return fmt.Errorf(customPrefix, err.Message)
}
}