-
Notifications
You must be signed in to change notification settings - Fork 6
/
client.go
710 lines (624 loc) · 16.4 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
package electrum
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"log"
"strconv"
"strings"
"sync"
"time"
)
// Version flag for the library
const Version = "0.4.1"
// Protocol tags
const (
Protocol10 = "1.0"
Protocol11 = "1.1"
Protocol12 = "1.2"
)
// Common errors
var (
ErrDeprecatedMethod = errors.New("DEPRECATED_METHOD")
ErrUnavailableMethod = errors.New("UNAVAILABLE_METHOD")
ErrRejectedTx = errors.New("REJECTED_TRANSACTION")
ErrUnreachableHost = errors.New("UNREACHABLE_HOST")
)
// Message Delimiter, according to the protocol specification
// http://docs.electrum.org/en/latest/protocol.html#format
const delimiter = byte('\n')
// 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 *log.Logger
}
// 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 *log.Logger
agent string
bgProcessing context.Context
cleanUp context.CancelFunc
resuming context.Context
stopResuming context.CancelFunc
sync.Mutex
}
type subscription struct {
method string
params []string
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,
})
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 = Protocol12
}
// 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"
}
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,
}
// Automatically send a 'server.version' or 'server.ping' request every 60 seconds as a keep-alive
// signal to the server
if options.KeepAlive {
client.ping = time.NewTicker(60 * time.Second)
go func() {
defer client.ping.Stop()
for {
select {
case <-client.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 := client.req("server.version", client.Version, client.Protocol).encode(); err == nil {
/* #nosec */
client.transport.sendMessage(b)
}
case <-client.bgProcessing.Done():
return
}
}
}()
}
// 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
}
// Build a request object
func (c *Client) req(name string, params ...string) *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 = []string{}
}
req := &request{
ID: c.counter,
Method: name,
Params: params,
}
c.counter++
return req
}
// Receive incoming network messages and the 'stop' signal
func (c *Client) handleMessages() {
for {
select {
case <-c.done:
for i := range c.subs {
c.removeSubscription(i)
}
c.cleanUp()
return
case err := <-c.transport.errors:
if c.log != nil {
c.log.Println(err)
}
case m := <-c.transport.messages:
if c.log != nil {
c.log.Println(m)
}
resp := &response{}
if err := json.Unmarshal(m, resp); err != nil {
break
}
// 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()
break
}
// 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() {
// 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.log.Printf("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
}
if err := c.transport.sendMessage(b); err != nil {
return nil, err
}
// Log request
if c.log != nil {
c.log.Println(req)
}
// Wait for the response
return <-res, 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:
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:
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
}
// AddressBalance will synchronously run a 'blockchain.address.get_balance' operation
//
// https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-address-get-balance
func (c *Client) AddressBalance(address string) (balance *Balance, err error) {
res, err := c.syncRequest(c.req("blockchain.address.get_balance", address))
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, &balance); err != nil {
return
}
return
}
// AddressHistory will synchronously run a 'blockchain.address.get_history' operation
//
// https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-address-get-history
func (c *Client) AddressHistory(address string) (list *[]Tx, err error) {
res, err := c.syncRequest(c.req("blockchain.address.get_history", address))
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, &list); err != nil {
return
}
return
}
// AddressMempool will synchronously run a 'blockchain.address.get_mempool' operation
//
// https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-address-get-mempool
func (c *Client) AddressMempool(address string) (list *[]Tx, err error) {
res, err := c.syncRequest(c.req("blockchain.address.get_mempool", address))
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, &list); err != nil {
return
}
return
}
// AddressListUnspent will synchronously run a 'blockchain.address.listunspent' operation
//
// https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-address-listunspent
func (c *Client) AddressListUnspent(address string) (list *[]Tx, err error) {
res, err := c.syncRequest(c.req("blockchain.address.listunspent", address))
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, &list); err != nil {
return
}
return
}
// BlockHeader will synchronously run a 'blockchain.block.get_header' operation
//
// https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-block-get-header
func (c *Client) BlockHeader(index int) (header *BlockHeader, err error) {
res, err := c.syncRequest(c.req("blockchain.block.get_header", strconv.Itoa(index)))
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
}
// 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)
log.Printf("%s", res.Result)
if err != nil {
return
}
if err = json.Unmarshal(b, &tm); err != nil {
return
}
return
}