This repository has been archived by the owner on Nov 8, 2021. It is now read-only.
forked from ordishs/go-bitcoin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
RPC.go
704 lines (577 loc) · 17.9 KB
/
RPC.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
package bitcoin
import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"strconv"
"time"
cache "github.com/patrickmn/go-cache"
"golang.org/x/sync/singleflight"
)
// A Bitcoind represents a Bitcoind client
type Bitcoind struct {
client *rpcClient
Storage *cache.Cache
group singleflight.Group
}
// New return a new bitcoind
func New(host string, port int, user, passwd string, useSSL bool) (*Bitcoind, error) {
rpcClient, err := newClient(host, port, user, passwd, useSSL)
if err != nil {
return nil, err
}
defaultExpiration := 5 * time.Second
cleanupInterval := 10 * time.Second
return &Bitcoind{
client: rpcClient,
Storage: cache.New(defaultExpiration, cleanupInterval),
group: singleflight.Group{},
}, nil
}
func (b *Bitcoind) call(method string, params []interface{}) (rpcResponse, error) {
key := fmt.Sprintf("%s|%v", method, params)
// Check cache
value, found := b.Storage.Get(key)
if found {
// fmt.Printf("CACHED: ")
return value.(rpcResponse), nil
}
// Combine memoized function with a cache store
value, err, _ := b.group.Do(key, func() (interface{}, error) {
data, innerErr := b.client.call(method, params)
if innerErr == nil {
b.Storage.Set(key, data, cache.DefaultExpiration)
}
return data, innerErr
})
return value.(rpcResponse), err
}
func (b *Bitcoind) read(method string, params []interface{}) (io.ReadCloser, error) {
return b.client.read(method, params)
}
// GetConnectionCount returns the number of connections to other nodes.
func (b *Bitcoind) GetConnectionCount() (count uint64, err error) {
r, err := b.call("getconnectioncount", nil)
if err != nil {
return 0, err
}
count, err = strconv.ParseUint(string(r.Result), 10, 64)
return
}
// GetBlockchainInfo returns the number of connections to other nodes.
func (b *Bitcoind) GetBlockchainInfo() (info BlockchainInfo, err error) {
r, err := b.call("getblockchaininfo", nil)
if err != nil {
return
}
if r.Err != nil {
rr := r.Err.(map[string]interface{})
err = fmt.Errorf("ERROR %s: %s", rr["code"], rr["message"])
return
}
err = json.Unmarshal(r.Result, &info)
return
}
// GetInfo returns the number of connections to other nodes.
func (b *Bitcoind) GetInfo() (info GetInfo, err error) {
r, err := b.call("getinfo", nil)
if err != nil {
return
}
if r.Err != nil {
rr := r.Err.(map[string]interface{})
err = fmt.Errorf("ERROR %s: %s", rr["code"], rr["message"])
return
}
err = json.Unmarshal(r.Result, &info)
return
}
// GetNetworkInfo returns the number of connections to other nodes.
func (b *Bitcoind) GetNetworkInfo() (info NetworkInfo, err error) {
r, err := b.call("getnetworkinfo", nil)
if err != nil {
return
}
if r.Err != nil {
rr := r.Err.(map[string]interface{})
err = fmt.Errorf("ERROR %s: %s", rr["code"], rr["message"])
return
}
err = json.Unmarshal(r.Result, &info)
return
}
// GetNetTotals returns the number of connections to other nodes.
func (b *Bitcoind) GetNetTotals() (totals NetTotals, err error) {
r, err := b.call("getnettotals", nil)
if err != nil {
return
}
if r.Err != nil {
rr := r.Err.(map[string]interface{})
err = fmt.Errorf("ERROR %s: %s", rr["code"], rr["message"])
return
}
err = json.Unmarshal(r.Result, &totals)
return
}
// GetMiningInfo comment
func (b *Bitcoind) GetMiningInfo() (info MiningInfo, err error) {
r, err := b.call("getmininginfo", nil)
if err != nil {
return
}
if r.Err != nil {
rr := r.Err.(map[string]interface{})
err = fmt.Errorf("ERROR %s: %s", rr["code"], rr["message"])
return
}
err = json.Unmarshal(r.Result, &info)
return
}
// Uptime returns the number of connections to other nodes.
func (b *Bitcoind) Uptime() (uptime uint64, err error) {
r, err := b.call("uptime", nil)
if err != nil {
return 0, err
}
uptime, err = strconv.ParseUint(string(r.Result), 10, 64)
return
}
// GetPeerInfo returns the number of connections to other nodes.
func (b *Bitcoind) GetPeerInfo() (info PeerInfo, err error) {
r, err := b.call("getpeerinfo", nil)
if err != nil {
return
}
if r.Err != nil {
rr := r.Err.(map[string]interface{})
err = fmt.Errorf("ERROR %s: %s", rr["code"], rr["message"])
return
}
err = json.Unmarshal(r.Result, &info)
return
}
// GetMempoolInfo comment
func (b *Bitcoind) GetMempoolInfo() (info MempoolInfo, err error) {
r, err := b.call("getmempoolinfo", nil)
if err != nil {
return
}
if r.Err != nil {
rr := r.Err.(map[string]interface{})
err = fmt.Errorf("ERROR %s: %s", rr["code"], rr["message"])
return
}
err = json.Unmarshal(r.Result, &info)
return
}
// GetRawMempool returns the number of connections to other nodes.
func (b *Bitcoind) GetRawMempool(details bool) (raw []byte, err error) {
p := []interface{}{details}
r, err := b.call("getrawmempool", p)
if err != nil {
return
}
if r.Err != nil {
rr := r.Err.(map[string]interface{})
err = fmt.Errorf("ERROR %s: %s", rr["code"], rr["message"])
return
}
//err = json.Unmarshal(r.Result, &raw)
raw, err = json.Marshal(r.Result)
return
}
// GetChainTxStats returns the number of connections to other nodes.
func (b *Bitcoind) GetChainTxStats(blockcount int) (stats ChainTXStats, err error) {
p := []interface{}{blockcount}
r, err := b.call("getchaintxstats", p)
if err != nil {
return
}
if r.Err != nil {
rr := r.Err.(map[string]interface{})
err = fmt.Errorf("ERROR %s: %s", rr["code"], rr["message"])
return
}
err = json.Unmarshal(r.Result, &stats)
return
}
// ValidateAddress returns the number of connections to other nodes.
func (b *Bitcoind) ValidateAddress(address string) (addr Address, err error) {
p := []interface{}{address}
r, err := b.call("validateaddress", p)
if err != nil {
return
}
if r.Err != nil {
rr := r.Err.(map[string]interface{})
err = fmt.Errorf("ERROR %s: %s", rr["code"], rr["message"])
return
}
err = json.Unmarshal(r.Result, &addr)
return
}
// GetHelp returns the number of connections to other nodes.
func (b *Bitcoind) GetHelp() (j []byte, err error) {
r, err := b.call("help", nil)
if err != nil {
return
}
j, err = json.Marshal(r.Result)
return
}
// GetBestBlockHash comment
func (b *Bitcoind) GetBestBlockHash() (hash string, err error) {
r, err := b.call("getbestblockhash", nil)
if err != nil {
return "", err
}
if err := json.Unmarshal(r.Result, &hash); err != nil {
return "", err
}
return
}
// GetBlockHash comment
func (b *Bitcoind) GetBlockHash(blockHeight int) (blockHash string, err error) {
p := []interface{}{blockHeight}
r, err := b.call("getblockhash", p)
if err != nil {
return "", err
}
if err := json.Unmarshal(r.Result, &blockHash); err != nil {
return "", err
}
return
}
// SendRawTransaction comment
func (b *Bitcoind) SendRawTransaction(hex string) (txid string, err error) {
r, err := b.call("sendrawtransaction", []interface{}{hex, true})
if err != nil {
return "", err
}
if err := json.Unmarshal(r.Result, &txid); err != nil {
return "", err
}
return
}
// SendRawTransactionWithoutFeeCheck comment
func (b *Bitcoind) SendRawTransactionWithoutFeeCheck(hex string) (txid string, err error) {
r, err := b.call("sendrawtransaction", []interface{}{hex, false, true})
if err != nil {
return "", err
}
if err := json.Unmarshal(r.Result, &txid); err != nil {
return "", err
}
return
}
// SignRawTransaction comment
func (b *Bitcoind) SignRawTransaction(hex string) (sr *SignRawTransactionResponse, err error) {
r, err := b.call("signrawtransaction", []interface{}{hex})
if err != nil {
return
}
if r.Err != nil {
rr := r.Err.(map[string]interface{})
err = fmt.Errorf("ERROR %s: %s", rr["code"], rr["message"])
return
}
err = json.Unmarshal(r.Result, &sr)
return
}
// GetBlock returns information about the block with the given hash.
func (b *Bitcoind) GetBlock(blockHash string) (block *Block, err error) {
r, err := b.call("getblock", []interface{}{blockHash})
if err != nil {
return
}
if r.Err != nil {
rr := r.Err.(map[string]interface{})
err = fmt.Errorf("ERROR %s: %s", rr["code"], rr["message"])
return
}
err = json.Unmarshal(r.Result, &block)
return
}
// GetRawBlock returns the raw bytes of the block with the given hash.
func (b *Bitcoind) GetRawBlock(blockHash string) ([]byte, error) {
r, err := b.call("getblock", []interface{}{blockHash, 0})
if err != nil {
return nil, err
}
var rawHex string
err = json.Unmarshal(r.Result, &rawHex)
if err != nil {
return nil, err
}
res, err := hex.DecodeString(rawHex)
if err != nil {
return nil, err
}
return res, nil
}
// GetRawBlockReader returns a reader of the block with the given hash.
func (b *Bitcoind) GetRawBlockReader(blockHash string) (io.ReadCloser, error) {
return b.read("getblock", []interface{}{blockHash, 0})
}
func (b *Bitcoind) GetRawBlockRest(blockHash string) (io.ReadCloser, error) {
resp, err := http.Get(fmt.Sprintf("%s/rest/block/%s.bin", b.client.serverAddr, blockHash))
if err != nil {
return nil, fmt.Errorf("Could not GET block: %v", err)
}
if resp.StatusCode != 200 {
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
return nil, fmt.Errorf("ERROR: code %d: %s", resp.StatusCode, data)
}
return resp.Body, nil
}
// GetBlockOverview returns basic information about the block with the given hash.
func (b *Bitcoind) GetBlockOverview(blockHash string) (block *BlockOverview, err error) {
r, err := b.call("getblock", []interface{}{blockHash})
if err != nil {
return
}
if r.Err != nil {
rr := r.Err.(map[string]interface{})
err = fmt.Errorf("ERROR %s: %s", rr["code"], rr["message"])
return
}
err = json.Unmarshal(r.Result, &block)
return
}
// GetBlockHeaderHex returns the block header hex for the given hash.
func (b *Bitcoind) GetBlockHeaderHex(blockHash string) (blockHeader *string, err error) {
r, err := b.call("getblockheader", []interface{}{blockHash, false})
if err != nil {
return
}
if r.Err != nil {
rr := r.Err.(map[string]interface{})
err = fmt.Errorf("ERROR %s: %s", rr["code"], rr["message"])
return
}
err = json.Unmarshal(r.Result, &blockHeader)
return
}
// GetBlockHeader returns the block header for the given hash.
func (b *Bitcoind) GetBlockHeader(blockHash string) (blockHeader *BlockHeader, err error) {
r, err := b.call("getblockheader", []interface{}{blockHash})
if err != nil {
return
}
if r.Err != nil {
rr := r.Err.(map[string]interface{})
err = fmt.Errorf("ERROR %s: %s", rr["code"], rr["message"])
return
}
err = json.Unmarshal(r.Result, &blockHeader)
return
}
// GetBlockHex returns information about the block with the given hash.
func (b *Bitcoind) GetBlockHex(blockHash string) (raw *string, err error) {
r, err := b.call("getblock", []interface{}{blockHash, 0})
if err != nil {
return
}
err = json.Unmarshal(r.Result, &raw)
return
}
// GetBlockHeaderAndCoinbase returns information about the block with the given hash.
func (b *Bitcoind) GetBlockHeaderAndCoinbase(blockHash string) (blockHeaderAndCoinbase *BlockHeaderAndCoinbase, err error) {
r, err := b.call("getblock", []interface{}{blockHash, 3})
if err != nil {
return
}
err = json.Unmarshal(r.Result, &blockHeaderAndCoinbase)
return
}
// GetRawTransaction returns raw transaction representation for given transaction id.
func (b *Bitcoind) GetRawTransaction(txID string) (rawTx *RawTransaction, err error) {
if txID == "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b" {
// This is the genesis coinbase transaction and cannot be retrieved in this way.
return &RawTransaction{
Hex: "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4d04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73ffffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000",
TxID: "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b",
Hash: "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b",
Version: 1,
Size: 204,
LockTime: 0,
Vin: []Vin{
{
Coinbase: "04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73",
Sequence: 4294967295,
},
},
Vout: []Vout{
{
Value: 50.00000000,
N: 0,
ScriptPubKey: ScriptPubKey{
ASM: "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f OP_CHECKSIG",
Hex: "4104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac",
ReqSigs: 1,
Type: "pubkey",
Addresses: []string{"1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa"},
},
},
},
BlockHash: "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f",
Time: 1231006505,
Blocktime: 1231006505,
}, nil
}
r, err := b.call("getrawtransaction", []interface{}{txID, 1})
if err != nil {
return
}
err = json.Unmarshal(r.Result, &rawTx)
return
}
// GetRawTransactionHex returns raw transaction representation for given transaction id.
func (b *Bitcoind) GetRawTransactionHex(txID string) (rawTx *string, err error) {
if txID == "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b" {
// This is the genesis coinbase transaction and cannot be retrieved in this way.
genesisHex := "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4d04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73ffffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000"
return &genesisHex, nil
}
r, err := b.call("getrawtransaction", []interface{}{txID, 0})
if err != nil {
return
}
err = json.Unmarshal(r.Result, &rawTx)
return
}
// GetBlockTemplate comment
func (b *Bitcoind) GetBlockTemplate(includeSegwit bool) (template *BlockTemplate, err error) {
params := gbtParams{}
if includeSegwit {
params = gbtParams{
Mode: "",
Capabilities: []string{},
Rules: []string{"segwit"},
}
}
r, err := b.call("getblocktemplate", []interface{}{params})
if err != nil {
return nil, err
}
if err := json.Unmarshal(r.Result, &template); err != nil {
return nil, err
}
return
}
// GetMiningCandidate comment
func (b *Bitcoind) GetMiningCandidate() (template *MiningCandidate, err error) {
r, err := b.call("getminingcandidate", nil)
if err != nil {
return nil, err
}
if err := json.Unmarshal(r.Result, &template); err != nil {
return nil, err
}
return
}
// SubmitBlock comment
func (b *Bitcoind) SubmitBlock(hexData string) (result string, err error) {
r, err := b.client.call("submitblock", []interface{}{hexData})
if err != nil || r.Err != nil || string(r.Result) != "null" {
msg := fmt.Sprintf("******* BLOCK SUBMIT FAILED with error: %+v and result: %s\n", err, string(r.Result))
return "", errors.New(msg)
}
return string(r.Result), nil
}
// SubmitMiningSolution comment
func (b *Bitcoind) SubmitMiningSolution(miningCandidateID string, nonce uint32, coinbase string, time uint32, version uint32) (result string, err error) {
params := submitMiningSolutionParams{
ID: miningCandidateID,
Nonce: nonce,
Coinbase: coinbase,
Time: time,
Version: version,
}
r, err := b.client.call("submitminingsolution", []interface{}{params})
if (err != nil && err.Error() != "") || r.Err != nil || (string(r.Result) != "null" && string(r.Result) != "true") {
msg := fmt.Sprintf("******* BLOCK SUBMIT FAILED with error: %+v and result: %s\n", err, string(r.Result))
return "", errors.New(msg)
}
return string(r.Result), nil
}
// GetDifficulty comment
func (b *Bitcoind) GetDifficulty() (difficulty float64, err error) {
r, err := b.call("getdifficulty", nil)
if err != nil {
return 0.0, err
}
difficulty, err = strconv.ParseFloat(string(r.Result), 64)
return
}
// DecodeRawTransaction comment
func (b *Bitcoind) DecodeRawTransaction(txHex string) (string, error) {
r, err := b.call("decoderawtransaction", []interface{}{txHex})
if err != nil {
return "", err
}
return string(r.Result), nil
}
// GetTxOut comment
func (b *Bitcoind) GetTxOut(txHex string, vout int, includeMempool bool) (string, error) {
r, err := b.call("gettxout", []interface{}{txHex, vout, includeMempool})
if err != nil {
return "", err
}
return string(r.Result), nil
}
// ListUnspent comment
func (b *Bitcoind) ListUnspent(addresses []string) (res []*UnspentTransaction, err error) {
var minConf uint32 = 0
var maxConf uint32 = 9999999
r, err := b.call("listunspent", []interface{}{minConf, maxConf, addresses})
if err != nil {
return
}
_ = json.Unmarshal(r.Result, &res)
for _, utxo := range res {
if utxo.Amount > 0 && utxo.Satoshis == 0 {
utxo.Satoshis = uint64(utxo.Amount * 100000000)
}
}
return
}
// SendToAddress comment
func (b *Bitcoind) SendToAddress(address string, amount float64) (string, error) {
r, err := b.call("sendtoaddress", []interface{}{address, amount})
if err != nil {
return "", err
}
var txid string
_ = json.Unmarshal(r.Result, &txid)
return txid, nil
}
// Generate for regtest
func (b *Bitcoind) Generate(amount float64) ([]string, error) {
r, err := b.call("generate", []interface{}{amount})
if err != nil {
return nil, err
}
var hashes []string
_ = json.Unmarshal(r.Result, &hashes)
return hashes, nil
}
// GenerateToAddress for regtest
func (b *Bitcoind) GenerateToAddress(amount float64, address string) ([]string, error) {
r, err := b.call("generatetoaddress", []interface{}{amount, address})
if err != nil {
return nil, err
}
var hashes []string
_ = json.Unmarshal(r.Result, &hashes)
return hashes, nil
}