forked from fairbank-io/electrum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubscription.go
69 lines (64 loc) · 1.71 KB
/
subscription.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
package electrum
import (
"context"
"encoding/json"
)
// NotifyBlockHeaders will setup a subscription for the method 'blockchain.headers.subscribe'
//
// https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-headers-subscribe
func (c *Client) NotifyBlockHeaders(ctx context.Context) (<-chan *BlockHeader, error) {
headers := make(chan *BlockHeader)
sub := &subscription{
ctx: ctx,
method: "blockchain.headers.subscribe",
messages: make(chan *response),
handler: func(m *response) {
if m.Result != nil {
h := &BlockHeader{}
b, _ := json.Marshal(m.Result)
json.Unmarshal(b, h)
headers <- h
}
if m.Params != nil {
for _, i := range m.Params.([]interface{}) {
h := &BlockHeader{}
b, _ := json.Marshal(i)
json.Unmarshal(b, h)
headers <- h
}
}
},
}
if err := c.startSubscription(sub); err != nil {
close(headers)
return nil, err
}
return headers, nil
}
// NotifyAddressTransactions will setup a subscription for the method 'blockchain.address.subscribe'
//
// https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-address-subscribe
func (c *Client) NotifyAddressTransactions(ctx context.Context, address string) (<-chan string, error) {
txs := make(chan string)
sub := &subscription{
ctx: ctx,
method: "blockchain.address.subscribe",
params: []string{address},
messages: make(chan *response),
handler: func(m *response) {
if m.Result != nil {
txs <- m.Result.(string)
}
if m.Params != nil {
for _, i := range m.Params.([]interface{}) {
txs <- i.(string)
}
}
},
}
if err := c.startSubscription(sub); err != nil {
close(txs)
return nil, err
}
return txs, nil
}