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
/
zmq.go
169 lines (141 loc) · 3.92 KB
/
zmq.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
package bitcoin
import (
"context"
"encoding/hex"
"fmt"
"log"
"sync"
"time"
"github.com/go-zeromq/zmq4"
)
// ZMQ struct
type ZMQ struct {
mu sync.RWMutex
address string
socket zmq4.Socket
connected bool
err error
topics []string
subscriptions map[string][]chan []string
}
// NewZMQ comment
func NewZMQ(host string, port int) *ZMQ {
return newZMQ(host, port, false, "hash")
}
// NewZMQWithRaw creates a bitcoin ZMQ listener with raw enabled
func NewZMQWithRaw(host string, port int) *ZMQ {
return newZMQ(host, port, true, "hash")
}
// NewZMQWithSubscribeOptionValue creates a bitcoin ZMQ listener with subscribe option value
func NewZMQWithSubscribeOptionValue(host string, port int, optionValue string) *ZMQ {
return newZMQ(host, port, false, optionValue)
}
func newZMQ(host string, port int, rawRequired bool, optionValue string) *ZMQ {
zmq := &ZMQ{
address: fmt.Sprintf("tcp://%s:%d", host, port),
subscriptions: make(map[string][]chan []string),
topics: []string{"hashblock", "hashtx", "discardedfrommempool", "removedfrommempoolblock"},
}
if rawRequired {
zmq.topics = append(zmq.topics, "rawblock")
zmq.topics = append(zmq.topics, "rawtx")
}
go func() {
for {
zmq.socket = zmq4.NewSub(context.Background(), zmq4.WithID(zmq4.SocketIdentity("sub")))
defer func() {
if zmq.connected {
zmq.socket.Close()
zmq.connected = false
}
}()
if err := zmq.socket.Dial(zmq.address); err != nil {
zmq.mu.Lock()
zmq.err = err
zmq.mu.Unlock()
log.Printf("Attempting to re-establish ZMQ connection in 5 seconds...")
time.Sleep(10 * time.Second)
continue
}
if err := zmq.socket.SetOption(zmq4.OptionSubscribe, optionValue); err != nil {
zmq.err = fmt.Errorf("%+v", err)
return
}
if rawRequired {
if err := zmq.socket.SetOption(zmq4.OptionSubscribe, "raw"); err != nil {
zmq.err = fmt.Errorf("%+v", err)
return
}
}
log.Printf("ZMQ: Subscribing to %s", zmq.address)
// 0MQ is so fast, we need to wait a while...
time.Sleep(time.Second)
for {
msg, err := zmq.socket.Recv()
if err != nil {
log.Printf("ERROR from zmq.socket.Recv() - %v\n", err)
break
} else {
if !zmq.connected {
zmq.connected = true
log.Printf("ZMQ: Subscription to %s established\n", zmq.address)
}
// log.Printf("%s: %s", string(msg.Frames[0]), hex.EncodeToString(msg.Frames[1]))
zmq.mu.RLock()
subscribers := zmq.subscriptions[string(msg.Frames[0])]
for _, subscriber := range subscribers {
subscriber <- []string{string(msg.Frames[0]), hex.EncodeToString(msg.Frames[1])}
}
zmq.mu.RUnlock()
}
}
if zmq.connected {
zmq.socket.Close()
zmq.connected = false
}
log.Printf("Attempting to re-establish ZMQ connection in 10 seconds...")
time.Sleep(10 * time.Second)
}
}()
return zmq
}
func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
// Subscribe comment
func (zmq *ZMQ) Subscribe(topic string, ch chan []string) error {
if !contains(zmq.topics, topic) {
return fmt.Errorf("topic must be %+v, received %q", zmq.topics, topic)
}
zmq.mu.Lock()
defer zmq.mu.Unlock()
if zmq.err != nil {
return fmt.Errorf("ERROR: ZMQ failed: %v", zmq.err)
}
subscribers := zmq.subscriptions[topic]
subscribers = append(subscribers, ch)
zmq.subscriptions[topic] = subscribers
return nil
}
// Unsubscribe comment
func (zmq *ZMQ) Unsubscribe(topic string, ch chan []string) error {
if !contains(zmq.topics, topic) {
return fmt.Errorf("topic must be %+v, received %q", zmq.topics, topic)
}
zmq.mu.Lock()
defer zmq.mu.Unlock()
subscribers := zmq.subscriptions[topic]
for i, channel := range subscribers {
if channel == ch {
subscribers = append(subscribers[:i], subscribers[i+1:]...)
break
}
}
zmq.subscriptions[topic] = subscribers
return nil
}