-
Notifications
You must be signed in to change notification settings - Fork 74
/
bitcoind.go
985 lines (885 loc) · 32.7 KB
/
bitcoind.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
// Package Bitcoind is client librari for bitcoind JSON RPC API
package bitcoind
import (
"encoding/json"
"errors"
"strconv"
)
const (
// VERSION represents bicoind package version
VERSION = 0.1
// DEFAULT_RPCCLIENT_TIMEOUT represent http timeout for rcp client
RPCCLIENT_TIMEOUT = 30
)
// A Bitcoind represents a Bitcoind client
type Bitcoind struct {
client *rpcClient
}
// New return a new bitcoind
func New(host string, port int, user, passwd string, useSSL bool, timeoutParam ...int) (*Bitcoind, error) {
var timeout int = RPCCLIENT_TIMEOUT
// If the timeout is specified in timeoutParam, allow it.
if len(timeoutParam) != 0 {
timeout = timeoutParam[0]
}
rpcClient, err := newClient(host, port, user, passwd, useSSL, timeout)
if err != nil {
return nil, err
}
return &Bitcoind{rpcClient}, nil
}
// BackupWallet Safely copies wallet.dat to destination,
// which can be a directory or a path with filename on the remote server
func (b *Bitcoind) BackupWallet(destination string) error {
r, err := b.client.call("backupwallet", []string{destination})
return handleError(err, &r)
}
// DumpPrivKey return private key as string associated to public <address>
func (b *Bitcoind) DumpPrivKey(address string) (privKey string, err error) {
r, err := b.client.call("dumpprivkey", []string{address})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &privKey)
return
}
// EncryptWallet encrypts the wallet with <passphrase>.
func (b *Bitcoind) EncryptWallet(passphrase string) error {
r, err := b.client.call("encryptwallet", []string{passphrase})
return handleError(err, &r)
}
// GetAccount returns the account associated with the given address.
func (b *Bitcoind) GetAccount(address string) (account string, err error) {
r, err := b.client.call("getaccount", []string{address})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &account)
return
}
// GetAccountAddress Returns the current bitcoin address for receiving
// payments to this account.
// If account does not exist, it will be created along with an
// associated new address that will be returned.
func (b *Bitcoind) GetAccountAddress(account string) (address string, err error) {
r, err := b.client.call("getaccountaddress", []string{account})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &address)
return
}
// GetAddressesByAccount return addresses associated with account <account>
func (b *Bitcoind) GetAddressesByAccount(account string) (addresses []string, err error) {
r, err := b.client.call("getaddressesbyaccount", []string{account})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &addresses)
return
}
// GetBalance return the balance of the server or of a specific account
// If [account] is "", returns the server's total available balance.
// If [account] is specified, returns the balance in the account
func (b *Bitcoind) GetBalance(account string, minconf uint64) (balance float64, err error) {
r, err := b.client.call("getbalance", []interface{}{account, minconf})
if err = handleError(err, &r); err != nil {
return
}
balance, err = strconv.ParseFloat(string(r.Result), 64)
return
}
type BlockHeader struct {
Hash string
Confirmations int
Height int
Version uint32
VersionHex string
Merkleroot string
Time int64
Mediantime int64
Nonce uint32
Bits uint32
Difficulty float64
Chainwork string
Txes int `json:"nTx"`
Previousblockhash string `json:"omitempty"`
Nextblockhash string `json:"omitempty"`
}
func (b *Bitcoind) GetBlockheader(blockHash string) (*BlockHeader, error) {
r, err := b.client.call("getblockheader", []string{blockHash})
if err = handleError(err, &r); err != nil {
return nil, err
}
var blockHeader BlockHeader
err = json.Unmarshal(r.Result, &blockHeader)
return &blockHeader, err
}
// GetBestBlockhash returns the hash of the best (tip) block in the longest block chain.
func (b *Bitcoind) GetBestBlockhash() (bestBlockHash string, err error) {
r, err := b.client.call("getbestblockhash", nil)
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &bestBlockHash)
return
}
// GetBlock returns information about the block with the given hash.
func (b *Bitcoind) GetBlock(blockHash string) (block Block, err error) {
r, err := b.client.call("getblock", []string{blockHash})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &block)
return
}
// GetBlockV2 returns verbose "2" information about the block with the given hash.
func (b *Bitcoind) GetBlockV2(blockHash string) (block BlockV2, err error) {
r, err := b.client.call("getblock", []interface{}{blockHash, 2})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &block)
return
}
// GetRawBlock returns information about the block with the given hash.
func (b *Bitcoind) GetRawBlock(blockHash string) (str string, err error) {
r, err := b.client.call("getblock", []interface{}{blockHash, false})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &str)
return
}
// GetBlockCount returns the number of blocks in the longest block chain.
func (b *Bitcoind) GetBlockCount() (count uint64, err error) {
r, err := b.client.call("getblockcount", nil)
if err = handleError(err, &r); err != nil {
return
}
count, err = strconv.ParseUint(string(r.Result), 10, 64)
return
}
// GetBlockHash returns hash of block in best-block-chain at <index>
func (b *Bitcoind) GetBlockHash(index uint64) (hash string, err error) {
r, err := b.client.call("getblockhash", []uint64{index})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &hash)
return
}
// getBlockTemplateParams reperesent parameters for GetBlockTemplate
type getBlockTemplateParams struct {
Mode string `json:"mode,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
}
// TODO a finir
// GetBlockTemplate Returns data needed to construct a block to work on.
// See BIP_0022 for more info on params.
func (b *Bitcoind) GetBlockTemplate(capabilities []string, mode string) (template string, err error) {
params := getBlockTemplateParams{
Mode: mode,
Capabilities: capabilities,
}
// TODO []interface{}{mode, capa}
r, err := b.client.call("getblocktemplate", []getBlockTemplateParams{params})
if err = handleError(err, &r); err != nil {
return
}
return
}
type ChainTip struct {
// The height of the current tip
Height int
// The hash of the highest tip
Hash string
// The length of the associated blockchain branch
BranchLen int
// The status of the current tip.
Status string
}
func (b *Bitcoind) GetChainTips() (tips []ChainTip, err error) {
r, err := b.client.call("getchaintips", nil)
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &tips)
return
}
// GetConnectionCount returns the number of connections to other nodes.
func (b *Bitcoind) GetConnectionCount() (count uint64, err error) {
r, err := b.client.call("getconnectioncount", nil)
if err = handleError(err, &r); err != nil {
return
}
count, err = strconv.ParseUint(string(r.Result), 10, 64)
return
}
// GetDifficulty returns the proof-of-work difficulty as a multiple of
// the minimum difficulty.
func (b *Bitcoind) GetDifficulty() (difficulty float64, err error) {
r, err := b.client.call("getdifficulty", nil)
if err = handleError(err, &r); err != nil {
return
}
difficulty, err = strconv.ParseFloat(string(r.Result), 64)
return
}
// GetGenerate returns true or false whether bitcoind is currently generating hashes
func (b *Bitcoind) GetGenerate() (generate bool, err error) {
r, err := b.client.call("getgenerate", nil)
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &generate)
return
}
// GetHashesPerSec returns a recent hashes per second performance measurement while generating.
func (b *Bitcoind) GetHashesPerSec() (hashpersec float64, err error) {
r, err := b.client.call("gethashespersec", nil)
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &hashpersec)
return
}
// See https://developer.bitcoin.org/reference/rpc/getmempoolinfo.html
type MemPoolInfo struct {
Loaded bool `json:"loaded"`
Size uint64 `json:"size"`
Bytes uint64 `json:"bytes"`
Usage uint64 `json:"usage"`
TotalFee float64 `json:"total_fee"`
MaxMemPool uint64 `json:"maxmempool"`
MemPoolMinFee float64 `json:"mempoolminfee"`
MinRelayTxFee float64 `json:"minrelaytxfee"`
UnbroadcastCount uint64 `json:"unbroadcastcount"`
}
// GetMemPoolInfo returns an object containing mem pool info
func (b *Bitcoind) GetMemPoolInfo() (*MemPoolInfo, error) {
r, err := b.client.call("getmempoolinfo", nil)
if err = handleError(err, &r); err != nil {
return nil, err
}
memPoolInfo := &MemPoolInfo{}
err = json.Unmarshal(r.Result, memPoolInfo)
return memPoolInfo, err
}
// See https://developer.bitcoin.org/reference/rpc/getblockchaininfo.html
type BlockChainInfo struct {
Chain string `json:"chain"`
Blocks uint64 `json:"blocks"`
Headers uint64 `json:"headers"`
BestBlockHash string `json:"bestblockhash"`
Difficulty float64 `json:"difficulty"`
Time uint64 `json:"time"`
Mediantime uint64 `json:"mediantime"`
VerificationProgress float64 `json:"verificationprogress"`
VerificationProgressInt uint64
InitialBlockDownload bool `json:"initialblockdownload"`
Chainwork string `json:"chainwork"`
SizeOnDisk uint64 `json:"size_on_disk"`
Pruned bool `json:"pruned"`
PruneHeight float64 `json:"pruneheight"`
AutomaticPruning bool `json:"automatic_pruning"`
PruneTargetSize float64 `json:"prune_target_size"`
Softforks map[string]interface{} `json:"softforks"`
Warnings string `json:"warnings"`
}
func (b *Bitcoind) GetBlockchainInfo() (*BlockChainInfo, error) {
r, err := b.client.call("getblockchaininfo", nil)
if err = handleError(err, &r); err != nil {
return nil, err
}
blockChainInfo := &BlockChainInfo{}
err = json.Unmarshal(r.Result, blockChainInfo)
blockChainInfo.VerificationProgressInt = uint64(blockChainInfo.VerificationProgressInt)
return blockChainInfo, err
}
// See https://developer.bitcoin.org/reference/rpc/getnetworkinfo.html
type NetworkInfo struct {
Version uint64 `json:"version"`
Subversion string `json:"subversion"`
ProtocolVersion uint64 `json:"protocolversion"`
LocalServices string `json:"localservices"`
LocalServicesNames []string `json:"localservicesnames"`
LocalRelay bool `json:"localrelay"`
Timeoffset uint64 `json:"timeoffset"`
Connections uint64 `json:"connections"`
ConnectionsIn uint64 `json:"connections_in"`
ConnectionsOut uint64 `json:"connections_out"`
NetworkActive bool `json:"networkactive"`
Networks []Network `json:"networks"`
RelayFee float64 `json:"relayfee"`
IncrementalFee float64 `json:"incrementalfee"`
LocalAddresses []LocalAddress `json:"localaddresses"`
Warnings string `json:"warnings"`
}
type LocalAddress struct {
Address string `json:"address"`
Port uint64 `json:"port"`
Score float64 `json:"score"`
}
type Network struct {
Name string `json:"name"`
Limited bool `json:"limited"`
Reachable bool `json:"reachable"`
Proxy string `json:"proxy"`
ProxyRandomizeCredentials bool `json:"proxy_randomize_credentials"`
}
func (b *Bitcoind) GetNetworkInfo() (*NetworkInfo, error) {
r, err := b.client.call("getnetworkinfo", nil)
if err = handleError(err, &r); err != nil {
return nil, err
}
networkInfo := &NetworkInfo{}
err = json.Unmarshal(r.Result, &networkInfo)
return networkInfo, err
}
// See https://developer.bitcoin.org/reference/rpc/getwalletinfo.html
type WalletInfo struct {
WalletName string `json:"walletname"`
WalletVersion uint64 `json:"walletversion"`
Format string `json:"format"`
TxCount uint64 `json:"txcount"`
KeyPoolOldest uint64 `json:"keypoololdest"`
KeyPoolSize uint64 `json:"keypoolsize"`
KeyPoolSizeHdInternal uint64 `json:"keypoolsize_hd_internal"`
UnlockedUntil uint64 `json:"unlocked_until"`
PayTxFee float64 `json:"paytxfee"`
HdSeedId string `json:"hdseedid"`
PrivateKeysEnabled bool `json:"private_keys_enabled"`
AvoidReuse bool `json:"avoid_reuse"`
Scanning Scanning `json:"scanning"`
Descriptors bool `json:"descriptors"`
}
type Scanning struct {
Duration uint64 `json:"duration"`
Progress float64 `json:"progress"`
}
func (b *Bitcoind) GetWalletInfo() (*WalletInfo, error) {
r, err := b.client.call("getwalletinfo", nil)
if err = handleError(err, &r); err != nil {
return nil, err
}
walletInfo := &WalletInfo{}
err = json.Unmarshal(r.Result, &walletInfo)
return walletInfo, err
}
// GetMiningInfo returns an object containing mining-related information
func (b *Bitcoind) GetMiningInfo() (miningInfo MiningInfo, err error) {
r, err := b.client.call("getmininginfo", nil)
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &miningInfo)
return
}
// GetNewAddress return a new address for account [account].
func (b *Bitcoind) GetNewAddress(account ...string) (addr string, err error) {
// 0 or 1 account
if len(account) > 1 {
err = errors.New("bad parameters for GetNewAddress: you can set 0 or 1 account")
return
}
r, err := b.client.call("getnewaddress", account)
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &addr)
return
}
// GetPeerInfo returns data about each connected node
func (b *Bitcoind) GetPeerInfo() (peerInfo []Peer, err error) {
r, err := b.client.call("getpeerinfo", nil)
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &peerInfo)
return
}
// GetRawChangeAddress Returns a new Bitcoin address, for receiving change.
// This is for use with raw transactions, NOT normal use.
func (b *Bitcoind) GetRawChangeAddress(account ...string) (rawAddress string, err error) {
// 0 or 1 account
if len(account) > 1 {
err = errors.New("bad parameters for GetRawChangeAddress: you can set 0 or 1 account")
return
}
r, err := b.client.call("getrawchangeaddress", account)
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &rawAddress)
return
}
// GetRawMempool returns all transaction ids in memory pool
func (b *Bitcoind) GetRawMempool() (txId []string, err error) {
r, err := b.client.call("getrawmempool", nil)
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &txId)
return
}
type VerboseTx struct {
// Virtual transaction size as defined in BIP 141
Size uint32
// Transaction fee in BTC
Fee float64
// Transaction fee with fee deltas used for mining priority
ModifiedFee float64
// Local time when tx entered pool
Time uint32
// Block height when tx entered pool
Height uint32
// Number of inpool descendents (including this one)
DescendantCount uint32
// Virtual transaction size of in-mempool descendants (including this one)
DescendantSize uint32
// Modified fees (see above) of in-mempool descendants (including this one)
DescendantFees float64
// Number of in-mempool ancestor transactions (including this one)
AncestorCount uint32
// Virtual transaction size of in-mempool ancestors (including this one)
AncestorSize uint32
// Modified fees (see above) of in-mempool ancestors (including this one)
AncestorFees uint32
// Hash of serialized transaction, including witness data
WTxId string
// Unconfirmed transactions used as inputs for this transaction
Depends []string
// Used by Bitcoin Unlimited RPC
SpentBy []string
}
// GetRawMempoolVerbose returns a verbose set of transactions
// map [TxId] => VerboseTx
func (b *Bitcoind) GetRawMempoolVerbose() (txs map[string]VerboseTx, err error) {
r, err := b.client.call("getrawmempool", []bool{true})
if err = handleError(err, &r); err != nil {
return
}
// marshall the data into the string txs map
err = json.Unmarshal(r.Result, &txs)
return
}
// GetRawTransaction returns raw transaction representation for given transaction id.
func (b *Bitcoind) GetRawTransaction(txId string, verbose bool) (rawTx interface{}, err error) {
intVerbose := 0
if verbose {
intVerbose = 1
}
r, err := b.client.call("getrawtransaction", []interface{}{txId, intVerbose})
if err = handleError(err, &r); err != nil {
return
}
if !verbose {
err = json.Unmarshal(r.Result, &rawTx)
} else {
var t RawTransaction
err = json.Unmarshal(r.Result, &t)
rawTx = t
}
return
}
// GetReceivedByAccount Returns the total amount received by addresses with [account] in
// transactions with at least [minconf] confirmations. If [account] is set to all return
// will include all transactions to all accounts
func (b *Bitcoind) GetReceivedByAccount(account string, minconf uint32) (amount float64, err error) {
if account == "all" {
account = ""
}
r, err := b.client.call("getreceivedbyaccount", []interface{}{account, minconf})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &amount)
return
}
// Returns the amount received by <address> in transactions with at least [minconf] confirmations.
// It correctly handles the case where someone has sent to the address in multiple transactions.
// Keep in mind that addresses are only ever used for receiving transactions. Works only for addresses
// in the local wallet, external addresses will always show 0.
func (b *Bitcoind) GetReceivedByAddress(address string, minconf uint32) (amount float64, err error) {
r, err := b.client.call("getreceivedbyaddress", []interface{}{address, minconf})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &amount)
return
}
// GetTransaction returns a Bitcoind.Transation struct about the given transaction
func (b *Bitcoind) GetTransaction(txid string) (transaction Transaction, err error) {
r, err := b.client.call("gettransaction", []interface{}{txid})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &transaction)
return
}
// GetTxOut returns details about an unspent transaction output (UTXO)
func (b *Bitcoind) GetTxOut(txid string, n uint32, includeMempool bool) (transactionOut UTransactionOut, err error) {
r, err := b.client.call("gettxout", []interface{}{txid, n, includeMempool})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &transactionOut)
return
}
// GetTxOutsetInfo returns statistics about the unspent transaction output (UTXO) set
func (b *Bitcoind) GetTxOutsetInfo() (txOutSet TransactionOutSet, err error) {
r, err := b.client.call("gettxoutsetinfo", nil)
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &txOutSet)
return
}
// GetWork
// If [data] is not specified, returns formatted hash data to work on
// If [data] is specified, tries to solve the block and returns true if it was successful.
func (b *Bitcoind) GetWork(data ...string) (response interface{}, err error) {
if len(data) > 1 {
err = errors.New("bad parameters for GetWork: you can set 0 or 1 parameter data")
return
}
var r rpcResponse
if len(data) == 0 {
r, err = b.client.call("getwork", nil)
if err = handleError(err, &r); err != nil {
return
}
var work Work
err = json.Unmarshal(r.Result, &work)
response = work
} else {
r, err = b.client.call("getwork", data)
if err = handleError(err, &r); err != nil {
return
}
var t bool
err = json.Unmarshal(r.Result, &t)
response = t
}
return
}
// ImportPrivKey Adds a private key (as returned by dumpprivkey) to your wallet.
// This may take a while, as a rescan is done, looking for existing transactions.
// Optional [rescan] parameter added in 0.8.0.
// Note: There's no need to import public key, as in ECDSA (unlike RSA) this
// can be computed from private key.
func (b *Bitcoind) ImportPrivKey(privKey, label string, rescan bool) error {
r, err := b.client.call("importprivkey", []interface{}{privKey, label, rescan})
return handleError(err, &r)
}
// KeyPoolRefill fills the keypool, requires wallet passphrase to be set.
func (b *Bitcoind) KeyPoolRefill() error {
r, err := b.client.call("keypoolrefill", nil)
return handleError(err, &r)
}
// ListAccounts returns Object that has account names as keys, account balances as values.
func (b *Bitcoind) ListAccounts(minconf int32) (accounts map[string]float64, err error) {
r, err := b.client.call("listaccounts", []int32{minconf})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &accounts)
return
}
// ListAddressResult represents a result composing ListAddressGroupings slice reply
type ListAddressResult struct {
Address string
Amount float64
Account string
}
// ListAddressGroupings returns all addresses in the wallet and info used for coincontrol.
func (b *Bitcoind) ListAddressGroupings() (list []ListAddressResult, err error) {
r, err := b.client.call("listaddressgroupings", nil)
if err = handleError(err, &r); err != nil {
return
}
// hum.....
var t [][][]interface{}
err = json.Unmarshal(r.Result, &t)
for _, tt := range t {
for _, ttt := range tt {
list = append(list, ListAddressResult{ttt[0].(string), ttt[1].(float64), ttt[2].(string)})
}
}
return
}
// ReceivedByAccount represents how much coin a account have recieved
type ReceivedByAccount struct {
// the account of the receiving addresses
Account string
// total amount received by addresses with this account
Amount float64
// number of confirmations of the most recent transaction included
Confirmations uint32
}
// ListReceivedByAccount Returns an slice of AccountRecieved:
func (b *Bitcoind) ListReceivedByAccount(minConf uint32, includeEmpty bool) (list []ReceivedByAccount, err error) {
r, err := b.client.call("listreceivedbyaccount", []interface{}{minConf, includeEmpty})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &list)
return
}
// ReceivedByAddress represents how much coin a account have recieved
type ReceivedByAddress struct {
// receiving address
Address string
// The corresponding account
Account string
// total amount received by addresses with this account
Amount float64
// number of confirmations of the most recent transaction included
Confirmations uint32
// Tansactions ID
TxIds []string
}
// ListReceivedByAccount Returns an slice of AccountRecieved:
func (b *Bitcoind) ListReceivedByAddress(minConf uint32, includeEmpty bool) (list []ReceivedByAddress, err error) {
r, err := b.client.call("listreceivedbyaddress", []interface{}{minConf, includeEmpty})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &list)
return
}
// ListSinceBlock
func (b *Bitcoind) ListSinceBlock(blockHash string, targetConfirmations uint32) (transaction []Transaction, err error) {
r, err := b.client.call("listsinceblock", []interface{}{blockHash, targetConfirmations})
if err = handleError(err, &r); err != nil {
return
}
type ts struct {
Transactions []Transaction
}
var result ts
if err = json.Unmarshal(r.Result, &result); err != nil {
return
}
transaction = result.Transactions
return
}
// ListTransactions returns up to [count] most recent transactions skipping the first
// [from] transactions for account [account]. If [account] not provided it'll return
// recent transactions from all accounts.
func (b *Bitcoind) ListTransactions(account string, count, from uint32) (transaction []Transaction, err error) {
r, err := b.client.call("listtransactions", []interface{}{account, count, from})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &transaction)
return
}
// ListUnspent returns array of unspent transaction inputs in the wallet.
func (b *Bitcoind) ListUnspent(minconf, maxconf uint32) (transactions []Transaction, err error) {
if maxconf > 999999 {
maxconf = 999999
}
r, err := b.client.call("listunspent", []interface{}{minconf, maxconf})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &transactions)
return
}
// UnspendableOutput represents a unspendable (locked) output
type UnspendableOutput struct {
TxId string `json:"txid"`
Vout uint64 `json:"vout"`
}
// ListLockUnspent returns list of temporarily unspendable outputs
func (b *Bitcoind) ListLockUnspent() (unspendableOutputs []UnspendableOutput, err error) {
r, err := b.client.call("listlockunspent", nil)
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &unspendableOutputs)
return
}
// LockUnspent updates(lock/unlock) list of temporarily unspendable outputs
func (b *Bitcoind) LockUnspent(lock bool, outputs []UnspendableOutput) (success bool, err error) {
r, err := b.client.call("lockunspent", []interface{}{lock, outputs})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &success)
return
}
// Move from one account in your wallet to another
func (b *Bitcoind) Move(formAccount, toAccount string, amount float64, minconf uint32, comment string) (success bool, err error) {
r, err := b.client.call("move", []interface{}{formAccount, toAccount, amount, minconf, comment})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &success)
return
}
// SendFrom send amount from fromAccount to toAddress
//
// amount is a real and is rounded to 8 decimal places.
// Will send the given amount to the given address, ensuring the account has a valid balance using [minconf] confirmations.
func (b *Bitcoind) SendFrom(fromAccount, toAddress string, amount float64, minconf uint32, comment, commentTo string) (txID string, err error) {
r, err := b.client.call("sendfrom", []interface{}{fromAccount, toAddress, amount, minconf, comment, commentTo})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &txID)
return
}
// SenMany send multiple times
func (b *Bitcoind) SendMany(fromAccount string, amounts map[string]float64, minconf uint32, comment string) (txID string, err error) {
r, err := b.client.call("sendmany", []interface{}{fromAccount, amounts, minconf, comment})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &txID)
return
}
// SendManySubtractFeeFrom send multiple times (with fee from)
// https://bitcoincore.org/en/doc/0.16.0/rpc/wallet/sendmany/
func (b *Bitcoind) SendManySubtractFeeFrom(fromAccount string, amounts map[string]float64, minconf uint32, comment string, feefrom []string) (txID string, err error) {
r, err := b.client.call("sendmany", []interface{}{fromAccount, amounts, minconf, comment, feefrom})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &txID)
return
}
// SendManyReplacable send multiple times (with fee from)
// https://bitcoincore.org/en/doc/0.16.0/rpc/wallet/sendmany/
func (b *Bitcoind) SendManyReplaceable(fromAccount string, amounts map[string]float64, minconf uint32, comment string, feefrom []string, replaceable *bool) (txID string, err error) {
var r rpcResponse
if replaceable != nil {
r, err = b.client.call("sendmany", []interface{}{fromAccount, amounts, minconf, comment, feefrom})
} else {
r, err = b.client.call("sendmany", []interface{}{fromAccount, amounts, minconf, comment, feefrom, *replaceable})
}
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &txID)
return
}
// SendToAddress send an amount to a given address
func (b *Bitcoind) SendToAddress(toAddress string, amount float64, comment, commentTo string) (txID string, err error) {
r, err := b.client.call("sendtoaddress", []interface{}{toAddress, amount, comment, commentTo})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &txID)
return
}
// SetAccount sets the account associated with the given address
func (b *Bitcoind) SetAccount(address, account string) error {
r, err := b.client.call("setaccount", []interface{}{address, account})
return handleError(err, &r)
}
// SetGenerate turns generation on or off.
// Generation is limited to [genproclimit] processors, -1 is unlimited.
func (b *Bitcoind) SetGenerate(generate bool, genProcLimit int32) error {
r, err := b.client.call("setgenerate", []interface{}{generate, genProcLimit})
return handleError(err, &r)
}
// SetTxFee set the transaction fee per kB
func (b *Bitcoind) SetTxFee(amount float64) error {
r, err := b.client.call("settxfee", []interface{}{amount})
return handleError(err, &r)
}
// Stop stop bitcoin server.
func (b *Bitcoind) Stop() error {
r, err := b.client.call("stop", nil)
return handleError(err, &r)
}
// SignMessage sign a message with the private key of an address
func (b *Bitcoind) SignMessage(address, message string) (sig string, err error) {
r, err := b.client.call("signmessage", []interface{}{address, message})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &sig)
return
}
// Verifymessage Verify a signed message.
func (b *Bitcoind) VerifyMessage(address, sign, message string) (success bool, err error) {
r, err := b.client.call("verifymessage", []interface{}{address, sign, message})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &success)
return
}
// ValidateAddressResponse represents a response to "validateaddress" call
type ValidateAddressResponse struct {
IsValid bool `json:"isvalid"`
Address string `json:"address"`
IsMine bool `json:"ismine"`
IsScript bool `json:"isscript"`
PubKey string `json:"pubkey"`
IsCompressed bool `json:"iscompressed"`
Account string `json:"account"`
}
// ValidateAddress return information about <bitcoinaddress>.
func (b *Bitcoind) ValidateAddress(address string) (va ValidateAddressResponse, err error) {
r, err := b.client.call("validateaddress", []interface{}{address})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &va)
return
}
// WalletLock Removes the wallet encryption key from memory, locking the wallet.
// After calling this method, you will need to call walletpassphrase again before being
// able to call any methods which require the wallet to be unlocked.
func (b *Bitcoind) WalletLock() error {
r, err := b.client.call("walletlock", nil)
return handleError(err, &r)
}
// walletPassphrase stores the wallet decryption key in memory for <timeout> seconds.
func (b *Bitcoind) WalletPassphrase(passPhrase string, timeout uint64) error {
r, err := b.client.call("walletpassphrase", []interface{}{passPhrase, timeout})
return handleError(err, &r)
}
func (b *Bitcoind) WalletPassphraseChange(oldPassphrase, newPassprhase string) error {
r, err := b.client.call("walletpassphrasechange", []interface{}{oldPassphrase, newPassprhase})
return handleError(err, &r)
}
// estimatesmartfee mode
// https://bitcoincore.org/en/doc/0.16.0/rpc/util/estimatesmartfee/
const (
ESTIMATE_MODE_UNSET string = "UNSET"
ESTIMATE_MODE_ECONOMICAL string = "ECONOMICAL"
ESTIMATE_MODE_CONSERVATIVE string = "CONSERVATIVE"
)
// EstimateSmartFeeResult result for call estimatesmartfee
// https://bitcoincore.org/en/doc/0.16.0/rpc/util/estimatesmartfee/
type EstimateSmartFeeResult struct {
FeeRate float64 `json:"feerate"`
Errors []string `json:"errors"`
Blocks int `json:"blocks"`
}
// EstimateSmartFee stimates the approximate fee per kilobyte needed for a transaction..
// https://bitcoincore.org/en/doc/0.16.0/rpc/util/estimatesmartfee/
func (b *Bitcoind) EstimateSmartFee(minconf int) (ret EstimateSmartFeeResult, err error) {
r, err := b.client.call("estimatesmartfee", []interface{}{minconf})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &ret)
return
}
// EstimateSmartFee stimates the approximate fee per kilobyte needed for a transaction..
// https://bitcoincore.org/en/doc/0.16.0/rpc/util/estimatesmartfee/
func (b *Bitcoind) EstimateSmartFeeWithMode(minconf int, mode string) (ret EstimateSmartFeeResult, err error) {
r, err := b.client.call("estimatesmartfee", []interface{}{minconf, mode})
if err = handleError(err, &r); err != nil {
return
}
err = json.Unmarshal(r.Result, &ret)
return
}