forked from fairbank-io/electrum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
1074 lines (895 loc) · 24.9 KB
/
client.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
package electrum
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"log/slog"
"strconv"
"strings"
"sync"
"time"
)
const (
// Version flag for the library
Version = "0.5.4"
// Protocol tags
Protocol10 = "1.0"
Protocol11 = "1.1"
Protocol12 = "1.2"
Protocol14 = "1.4"
Protocol14_2 = "1.4.2"
BitcoinBase = 1e8
// Message Delimiter, according to the protocol specification
// http://docs.electrum.org/en/latest/protocol.html#format
delimiter = byte('\n')
comma = ","
arrayStart = "["
arrayEnd = "]"
)
// Common errors
var (
ErrDeprecatedMethod = errors.New("DEPRECATED_METHOD")
ErrUnavailableMethod = errors.New("UNAVAILABLE_METHOD")
ErrRejectedTx = errors.New("REJECTED_TRANSACTION")
ErrUnreachableHost = errors.New("UNREACHABLE_HOST")
)
// Options define the available configuration options
type Options struct {
// Address of the server to use for network communications
Address string
// Version advertised by the client instance
Version string
// Protocol version preferred by the client instance
Protocol string
// If set to true, will enable the client to continuously dispatch
// a 'server.version' operation every 60 seconds
KeepAlive bool
// Agent identifier that will be transmitted to the server when required;
// will be concatenated with the client version
Agent string
// If provided, will be used to setup a secure network connection with the server
TLS *tls.Config
// If provided, will be used as logging sink
Log *slog.Logger
// Timeout for network operations
Timeout time.Duration
// The maximum number of transactions to fetch in a single batch
MaxBatchSize uint32
}
// Client defines the protocol client instance structure and interface
type Client struct {
// Address of the remote server to use for communication
Address string
// Version of the client
Version string
// Protocol version preferred by the client instance
Protocol string
done chan bool
transport *transport
counter int
subs map[int]*subscription
ping *time.Ticker
log *slog.Logger
agent string
bgProcessing context.Context
cleanUp context.CancelFunc
resuming context.Context
stopResuming context.CancelFunc
sync.Mutex
txCache *TxCache
maxBatchSize uint32
}
type subscription struct {
method string
params []any
messages chan *response
handler func(*response)
ctx context.Context
}
// New will create and start processing on a new client instance
func New(options *Options) (*Client, error) {
t, err := getTransport(&transportOptions{
address: options.Address,
tls: options.TLS,
timeout: options.Timeout,
})
if err != nil {
return nil, err
}
// By default use the latest supported protocol version
// https://electrumx.readthedocs.io/en/latest/protocol-changes.html
if options.Protocol == "" {
options.Protocol = Protocol14_2
}
// Use library version as default client version
if options.Version == "" {
options.Version = Version
}
// Use library identifier as default agent name
if options.Agent == "" {
options.Agent = "fairbank-electrum"
}
txCache, err := NewTxCache(nil)
if err != nil {
return nil, err
}
if options.MaxBatchSize == 0 {
options.MaxBatchSize = 80
}
ctx, cancel := context.WithCancel(context.Background())
client := &Client{
transport: t,
counter: 0,
bgProcessing: ctx,
cleanUp: cancel,
done: make(chan bool),
subs: make(map[int]*subscription),
log: options.Log,
agent: fmt.Sprintf("%s-%s", options.Agent, options.Version),
Address: options.Address,
Version: options.Version,
Protocol: options.Protocol,
txCache: txCache,
maxBatchSize: options.MaxBatchSize,
}
// Automatically send a 'server.version' or 'server.ping' request every 60 seconds as a keep-alive
// signal to the server
if options.KeepAlive {
client.keepAlive()
}
// Monitor transport state
go func() {
for {
select {
case s := <-client.transport.state:
client.Lock()
count := len(client.subs)
client.Unlock()
if s == Reconnected && count > 0 {
go client.resumeSubscriptions()
}
case <-client.bgProcessing.Done():
return
}
}
}()
go client.handleMessages()
return client, nil
}
func (c *Client) keepAlive() {
c.ping = time.NewTicker(60 * time.Second)
go func() {
defer c.ping.Stop()
for {
select {
case <-c.ping.C:
// Deliberately ignore errors produced by "ping" messages
// "server.ping" is not recognized by the server in the current release (1.4.3)
if b, err := c.req("server.version", c.Version, c.Protocol).encode(); err == nil {
/* #nosec */
err = c.transport.sendMessage(b)
if err != nil && c.log != nil {
c.log.Error("%v", err)
}
}
case <-c.bgProcessing.Done():
return
}
}
}()
}
func (c *Client) debug(msg string, args ...any) {
if c.log != nil {
c.log.Debug(fmt.Sprintf(msg, args...))
}
}
func (c *Client) error(msg string, args ...any) {
if c.log != nil {
c.log.Error(fmt.Sprintf(msg, args...))
}
}
// Build a request object
func (c *Client) req(name string, params ...any) *request {
c.Lock()
defer c.Unlock()
// If no parameters are specified send an empty array
// http://docs.electrum.org/en/latest/protocol.html#request
if len(params) == 0 {
params = []any{}
}
req := &request{
ID: c.counter,
Method: name,
Params: params,
}
c.counter++
return req
}
// Build a batch request object
func (c *Client) batchReq(name string, params [][]any) []*request {
requests := make([]*request, len(params))
for i, p := range params {
requests[i] = c.req(name, p...)
}
return requests
}
// Receive incoming network messages and the 'stop' signal
func (c *Client) handleMessages() {
for {
select {
case <-c.done:
for id := range c.subs {
c.removeSubscription(id)
}
c.cleanUp()
return
case err := <-c.transport.errors:
c.error("transport error: %s", err)
case m := <-c.transport.messages:
c.debug("received msg: %s", m)
var result interface{}
if err := json.Unmarshal(m, &result); err != nil {
c.error("error unmarshalling any: %v\n", err)
break
}
var responses []*response
if _, ok := result.([]interface{}); ok {
// Batch response
if err := json.Unmarshal(m, &responses); err != nil {
c.error("error unmarshalling batch responses: %v\n", err)
break
}
} else {
// Single response
resp := &response{}
if err := json.Unmarshal(m, resp); err != nil {
c.error("error unmarshalling one response: %v\n", err)
break
}
responses = append(responses, resp)
}
for _, resp := range responses {
c.handleResponse(resp)
}
}
}
}
func (c *Client) handleResponse(resp *response) {
// Message routed by method name
if resp.Method != "" {
c.Lock()
for _, sub := range c.subs {
if sub.method == resp.Method {
sub.messages <- resp
}
}
c.Unlock()
return
}
// Message routed by ID
c.Lock()
sub, ok := c.subs[resp.ID]
c.Unlock()
if ok {
sub.messages <- resp
}
}
// Remove and existing messages subscription
func (c *Client) removeSubscription(id int) {
c.Lock()
defer c.Unlock()
sub, ok := c.subs[id]
if ok {
close(sub.messages)
delete(c.subs, id)
}
}
// Restart processing of existing subscriptions; intended to be triggered after
// recovering from a dropped connection
func (c *Client) resumeSubscriptions() {
c.Lock()
defer c.Unlock()
// Handle existing resume attempts
if c.stopResuming != nil {
c.stopResuming()
}
c.resuming, c.stopResuming = context.WithCancel(context.Background())
// Wait for the connection to be responsive
rt := time.NewTicker(2 * time.Second)
defer rt.Stop()
WAIT:
for {
select {
case <-rt.C:
if _, err := c.ServerVersion(); err == nil {
break WAIT
}
case <-c.resuming.Done():
return
case <-c.bgProcessing.Done():
return
}
}
// Restart existing subscriptions
for id, sub := range c.subs {
c.removeSubscription(id)
sub.messages = make(chan *response)
if err := c.startSubscription(sub); err != nil {
c.error("failed to resume subscription '%s' with error: %s\n", sub.method, err)
}
}
}
// Start a subscription processing loop
func (c *Client) startSubscription(sub *subscription) error {
// Start processing loop
// Will be terminating when closing the subscription's context or
// by closing it's messages channel
go func() {
for {
select {
case msg, ok := <-sub.messages:
if !ok {
return
}
sub.handler(msg)
case <-sub.ctx.Done():
return
}
}
}()
// Register subscription
req := c.req(sub.method, sub.params...)
c.Lock()
c.subs[req.ID] = sub
c.Unlock()
// Send request to the server
b, err := req.encode()
if err != nil {
c.removeSubscription(req.ID)
return err
}
if err := c.transport.sendMessage(b); err != nil {
c.removeSubscription(req.ID)
return err
}
return nil
}
// Dispatch a synchronous request, i.e. wait for it's result
func (c *Client) syncRequest(req *request) (*response, error) {
// Setup a subscription for the request with proper cleanup
res := make(chan *response)
c.Lock()
c.subs[req.ID] = &subscription{messages: res}
c.Unlock()
defer c.removeSubscription(req.ID)
// Encode and dispatch the request
b, err := req.encode()
if err != nil {
return nil, err
}
b = append(b, delimiter)
// Log request
c.debug("sending msg: %s", b)
if err := c.transport.sendMessage(b); err != nil {
return nil, err
}
// Wait for the response
return <-res, nil
}
func encodeBatch(reqs []*request) ([]byte, error) {
reqsJson := make([]string, len(reqs))
for i, req := range reqs {
x, err := req.encode()
if err != nil {
return nil, err
}
reqsJson[i] = string(x)
}
return []byte(arrayStart + strings.Join(reqsJson, comma) + arrayEnd), nil
}
// Dispatch a batch of synchronous requests, i.e. wait for it's result
func (c *Client) syncBatchRequest(reqs []*request) ([]*response, error) {
reqMap := make(map[int]int, len(reqs))
// Setup a subscription for the request with proper cleanup
res := make(chan *response)
c.Lock()
for i, req := range reqs {
c.subs[req.ID] = &subscription{messages: res}
reqMap[req.ID] = i
}
c.Unlock()
// Encode and dispatch the request
b, err := encodeBatch(reqs)
if err != nil {
return nil, err
}
b = append(b, delimiter)
// Log request
c.debug("sending msg: %s", b)
if err := c.transport.sendMessage(b); err != nil {
return nil, err
}
// Wait for the response
respCount := 0
responses := make([]*response, len(reqs))
for resp := range res {
c.Lock()
delete(c.subs, resp.ID)
c.Unlock()
responses[reqMap[resp.ID]] = resp
respCount++
if respCount == len(reqs) {
close(res)
}
}
return responses, nil
}
// Close will finish execution and properly terminate the underlying network transport
func (c *Client) Close() {
c.transport.close()
close(c.done)
}
// ServerPing will send a ping message to the server to ensure it is responding, and to keep the
// session alive. The server may disconnect clients that have sent no requests for roughly 10 minutes.
//
// https://electrumx.readthedocs.io/en/latest/protocol-methods.html#server-ping
func (c *Client) ServerPing() error {
switch c.Protocol {
case Protocol12:
fallthrough
case Protocol14:
fallthrough
case Protocol14_2:
res, err := c.syncRequest(c.req("server.ping"))
if err != nil {
return err
}
if res.Error != nil {
return errors.New(res.Error.Message)
}
return nil
default:
return ErrUnavailableMethod
}
}
// ServerVersion will synchronously run a 'server.version' operation
//
// https://electrumx.readthedocs.io/en/latest/protocol-methods.html#server-version
func (c *Client) ServerVersion() (*VersionInfo, error) {
res, err := c.syncRequest(c.req("server.version", c.agent, c.Protocol))
if err != nil {
return nil, err
}
if res.Error != nil {
return nil, errors.New(res.Error.Message)
}
info := &VersionInfo{}
switch c.Protocol {
case Protocol10:
info.Software = res.Result.(string)
case Protocol11:
fallthrough
case Protocol12:
fallthrough
case Protocol14:
fallthrough
case Protocol14_2:
var d []string
b, err := json.Marshal(res.Result)
if err != nil {
return nil, err
}
if err = json.Unmarshal(b, &d); err != nil {
return nil, err
}
info.Software = d[0]
info.Protocol = d[1]
}
return info, nil
}
// ServerBanner will synchronously run a 'server.banner' operation
//
// https://electrumx.readthedocs.io/en/latest/protocol-methods.html#server-banner
func (c *Client) ServerBanner() (string, error) {
res, err := c.syncRequest(c.req("server.banner"))
if err != nil {
return "", err
}
if res.Error != nil {
return "", errors.New(res.Error.Message)
}
return res.Result.(string), nil
}
// ServerDonationAddress will synchronously run a 'server.donation_address' operation
//
// https://electrumx.readthedocs.io/en/latest/protocol-methods.html#server-donation-address
func (c *Client) ServerDonationAddress() (string, error) {
res, err := c.syncRequest(c.req("server.donation_address"))
if err != nil {
return "", err
}
if res.Error != nil {
return "", errors.New(res.Error.Message)
}
return res.Result.(string), nil
}
// ServerFeatures returns a list of features and services supported by the server
//
// https://electrumx.readthedocs.io/en/latest/protocol-methods.html#server-donation-address
func (c *Client) ServerFeatures() (*ServerInfo, error) {
info := new(ServerInfo)
switch c.Protocol {
case Protocol10:
return nil, ErrUnavailableMethod
default:
res, err := c.syncRequest(c.req("server.features"))
if err != nil {
return nil, err
}
if res.Error != nil {
return nil, errors.New(res.Error.Message)
}
b, err := json.Marshal(res.Result)
if err != nil {
return nil, err
}
if err = json.Unmarshal(b, &info); err != nil {
return nil, err
}
}
return info, nil
}
// ServerPeers returns a list of peer servers
//
// https://electrumx.readthedocs.io/en/latest/protocol-methods.html#server-peers-subscribe
func (c *Client) ServerPeers() (peers []*Peer, err error) {
res, err := c.syncRequest(c.req("server.peers.subscribe"))
if err != nil {
return
}
if res.Error != nil {
err = errors.New(res.Error.Message)
return
}
var list []interface{}
b, err := json.Marshal(res.Result)
if err != nil {
return
}
if err = json.Unmarshal(b, &list); err != nil {
return
}
for _, l := range list {
p := &Peer{
Address: l.([]interface{})[0].(string),
Name: l.([]interface{})[1].(string),
}
b, err := json.Marshal(l.([]interface{})[2])
if err != nil {
continue
}
if err = json.Unmarshal(b, &p.Features); err != nil {
continue
}
peers = append(peers, p)
}
return
}
// ScriptHashBalanceBalance will synchronously run a 'blockchain.scripthash.get_balance' operation
//
// https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-scripthash-get-balance
func (c *Client) ScriptHashBalance(scriptHash string) (*Balance, error) {
balance := new(Balance)
res, err := c.syncRequest(c.req("blockchain.scripthash.get_balance", scriptHash))
if err != nil {
return nil, fmt.Errorf("error getting balance for scripthash %s: %w", scriptHash, err)
}
if res.Error != nil {
return nil, fmt.Errorf("error getting balance for scripthash %s: %w", scriptHash, errors.New(res.Error.Message))
}
b, err := json.Marshal(res.Result)
if err != nil {
return nil, fmt.Errorf("error getting balance for scripthash %s: %w", scriptHash, err)
}
if err = json.Unmarshal(b, balance); err != nil {
return nil, fmt.Errorf("error getting balance for scripthash %s: %w", scriptHash, err)
}
return balance, nil
}
// ScriptHashHistory will synchronously run a 'blockchain.scripthash.get_history' operation
//
// https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-scripthash-get-history
func (c *Client) ScriptHashHistory(scriptHash string) ([]Tx, error) {
list := []Tx{}
res, err := c.syncRequest(c.req("blockchain.scripthash.get_history", scriptHash))
if err != nil {
return nil, fmt.Errorf("error getting history for scripthash %s: %w", scriptHash, err)
}
if res.Error != nil {
return nil, fmt.Errorf("error getting history for scripthash %s: %w", scriptHash, errors.New(res.Error.Message))
}
b, err := json.Marshal(res.Result)
if err != nil {
return nil, fmt.Errorf("error getting history for scripthash %s: %w", scriptHash, err)
}
if err = json.Unmarshal(b, &list); err != nil {
return nil, fmt.Errorf("error getting history for scripthash %s: %w", scriptHash, err)
}
return list, nil
}
// ScriptHashMempool will synchronously run a 'blockchain.scripthash.get_mempool' operation
//
// https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-scripthash-get-mempool
func (c *Client) ScriptHashMempool(scripthash string) ([]MempoolTx, error) {
list := []MempoolTx{}
res, err := c.syncRequest(c.req("blockchain.scripthash.get_mempool", scripthash))
if err != nil {
return nil, fmt.Errorf("error getting mempool for scripthash %s: %w", scripthash, err)
}
if res.Error != nil {
err = errors.New(res.Error.Message)
return nil, fmt.Errorf("error getting mempool for scripthash %s: %w", scripthash, err)
}
b, err := json.Marshal(res.Result)
if err != nil {
return nil, fmt.Errorf("error getting mempool for scripthash %s: %w", scripthash, err)
}
if err = json.Unmarshal(b, &list); err != nil {
return nil, fmt.Errorf("error getting mempool for scripthash %s: %w", scripthash, err)
}
return list, nil
}
// ScriptHashListUnspent will synchronously run a 'blockchain.scripthash.listunspent' operation
//
// https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-scripthash-listunspent
func (c *Client) ScriptHashListUnspent(scripthash string) ([]UnspentTx, error) {
list := []UnspentTx{}
res, err := c.syncRequest(c.req("blockchain.scripthash.listunspent", scripthash))
if err != nil {
return nil, fmt.Errorf("error getting listunspent for scripthash %s: %w", scripthash, err)
}
if res.Error != nil {
err = errors.New(res.Error.Message)
return nil, fmt.Errorf("error getting listunspent for scripthash %s: %w", scripthash, err)
}
b, err := json.Marshal(res.Result)
if err != nil {
return nil, fmt.Errorf("error getting listunspent for scripthash %s: %w", scripthash, err)
}
if err = json.Unmarshal(b, &list); err != nil {
return nil, fmt.Errorf("error getting listunspent for scripthash %s: %w", scripthash, err)
}
return list, nil
}
// BlockHeader will synchronously run a 'blockchain.block.header' operation
//
// https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-block-header
func (c *Client) BlockHeader(index int) (header *BlockHeader, err error) {
res, err := c.syncRequest(c.req("blockchain.block.header", index, index+1))
if err != nil {
return
}
if res.Error != nil {
err = errors.New(res.Error.Message)
return
}
b, err := json.Marshal(res.Result)
if err != nil {
return
}
if err = json.Unmarshal(b, &header); err != nil {
return
}
return
}
// BroadcastTransaction will synchronously run a 'blockchain.transaction.broadcast' operation
//
// https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-transaction-broadcast
func (c *Client) BroadcastTransaction(hex string) (string, error) {
res, err := c.syncRequest(c.req("blockchain.transaction.broadcast", hex))
if err != nil {
return "", err
}
if res.Result == nil || strings.Contains(res.Result.(string), "rejected") {
return "", ErrRejectedTx
}
return res.Result.(string), nil
}
// GetTransaction will synchronously run a 'blockchain.transaction.get' operation
//
// https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain.transaction.get
func (c *Client) GetTransaction(hash string) (string, error) {
res, err := c.syncRequest(c.req("blockchain.transaction.get", hash))
if err != nil {
return "", err
}
if res.Error != nil {
return "", errors.New(res.Error.Message)
}
return res.Result.(string), nil
}
func (c *Client) GetVerboseTransaction(hash string) (*VerboseTx, error) {
tx := new(VerboseTx)
if ok := c.txCache.Load(hash, tx); ok {
c.debug("Tx %s found in cache", hash)
return tx, nil
}
res, err := c.syncRequest(c.req("blockchain.transaction.get", hash, true))
if err != nil {
return nil, fmt.Errorf("error getting verbose transaction %s: %w", hash, err)
}
if res.Error != nil {
return nil, fmt.Errorf("error getting verbose transaction %s: %w", hash, errors.New(res.Error.Message))
}
b, err := json.Marshal(res.Result)
if err != nil {
return nil, fmt.Errorf("error getting verbose transaction %s: %w", hash, err)
}
if err = json.Unmarshal(b, tx); err != nil {
return nil, fmt.Errorf("error getting verbose transaction %s: %w", hash, err)
}
if tx.Confirmations > 0 {
err := c.txCache.Store(hash, *tx)
if err != nil {
c.error("Store tx %s in cache failed: %v", hash, err)
}
}
return tx, nil
}
// EstimateFee will synchronously run a 'blockchain.estimatefee' operation
//
// https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-estimatefee
func (c *Client) EstimateFee(blocks int) (float64, error) {
res, err := c.syncRequest(c.req("blockchain.estimatefee", strconv.Itoa(blocks)))
if err != nil {
return 0, err
}
if res.Error != nil {
return 0, errors.New(res.Error.Message)
}
return res.Result.(float64), nil
}
// TransactionMerkle will synchronously run a 'blockchain.transaction.get_merkle' operation
//
// https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-transaction-get-merkle
func (c *Client) TransactionMerkle(tx string, height int) (tm *TxMerkle, err error) {
res, err := c.syncRequest(c.req("blockchain.transaction.get_merkle", tx, strconv.Itoa(height)))
if err != nil {
return
}
if res.Error != nil {
err = errors.New(res.Error.Message)
return
}
b, err := json.Marshal(res.Result)
if err != nil {
return
}
if err = json.Unmarshal(b, &tm); err != nil {
return
}
return
}
// GetVerboseTransactionBatch gets the VerboseTx from a batch of transactions.
func (c *Client) GetVerboseTransactionBatch(
hashes []string,
) ([]*VerboseTx, error) {
txs := make([]*VerboseTx, len(hashes))
params := make([][]any, 0, len(hashes))
paramsMap := make(map[int]int, len(hashes))
for i, hash := range hashes {
tx := new(VerboseTx)
// if tx is in cache, use it
if ok := c.txCache.Load(hash, tx); ok {
txs[i] = tx
continue
}
params = append(params, []any{hash, true})
paramsMap[len(params)-1] = i
}
if len(params) == 0 {
return txs, nil
}
res, err := c.syncBatchRequest(c.batchReq("blockchain.transaction.get", params))
if err != nil {
return nil, err
}
for i, r := range res {
if r.Error != nil {
return nil, errors.New(r.Error.Message)
}
tx := new(VerboseTx)
b, err := json.Marshal(r.Result)
if err != nil {
return nil, err
}
if err = json.Unmarshal(b, tx); err != nil {
return nil, err
}
txs[paramsMap[i]] = tx
if tx.Confirmations > 0 {
err := c.txCache.Store(tx.TxID, *tx)
if err != nil {
c.error("Store tx %s in cache failed: %v", tx.TxID, err)
}
}
}
return txs, nil
}
func (c *Client) EnrichVin(vins []Vin) ([]VinWithPrevout, error) {
hashes := make([]string, len(vins))
for i, vin := range vins {
hashes[i] = vin.TxID
}
vinWithPrevouts := make([]VinWithPrevout, len(vins))
for i := 0; i <= len(hashes)/int(c.maxBatchSize); i++ {
start := i * int(c.maxBatchSize)
end := start + int(c.maxBatchSize)
if end > len(hashes) {
end = len(hashes)
}
batchHashes := hashes[start:end]
if len(batchHashes) == 0 {
break
}