forked from blinklabs-io/adder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmempool.go
More file actions
330 lines (301 loc) · 7.15 KB
/
mempool.go
File metadata and controls
330 lines (301 loc) · 7.15 KB
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
// Copyright 2025 Blink Labs Software
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package mempool
import (
"errors"
"fmt"
"sync"
"time"
"github.com/blinklabs-io/adder/event"
"github.com/blinklabs-io/adder/plugin"
ouroboros "github.com/blinklabs-io/gouroboros"
"github.com/blinklabs-io/gouroboros/ledger"
localtxmonitor "github.com/blinklabs-io/gouroboros/protocol/localtxmonitor"
)
const (
defaultPollInterval = 5 * time.Second
)
type Mempool struct {
logger plugin.Logger
network string
networkMagic uint32
socketPath string
address string
ntcTcp bool
includeCbor bool
pollIntervalStr string
pollInterval time.Duration
eventChan chan event.Event
errorChan chan error
doneChan chan struct{}
wg sync.WaitGroup
oConn *ouroboros.Connection
dialFamily string
dialAddress string
seenTxHashes map[string]struct{}
}
// New returns a new Mempool input plugin
func New(opts ...MempoolOptionFunc) *Mempool {
m := &Mempool{}
for _, opt := range opts {
opt(m)
}
return m
}
// Start connects to the node and starts polling the mempool
func (m *Mempool) Start() error {
if m.doneChan != nil {
close(m.doneChan)
m.wg.Wait()
}
if m.oConn != nil {
_ = m.oConn.Close()
m.oConn = nil
}
if m.eventChan != nil {
close(m.eventChan)
m.eventChan = nil
}
if m.errorChan != nil {
close(m.errorChan)
m.errorChan = nil
}
m.eventChan = make(chan event.Event, 10)
m.errorChan = make(chan error, 1)
m.doneChan = make(chan struct{})
if err := m.setupConnection(); err != nil {
return err
}
m.oConn.LocalTxMonitor().Client.Start()
m.wg.Add(1)
go m.pollLoop()
return nil
}
// Stop shuts down the connection and stops polling
func (m *Mempool) Stop() error {
if m.doneChan != nil {
close(m.doneChan)
m.doneChan = nil
}
if m.oConn != nil {
_ = m.oConn.Close()
m.oConn = nil
}
m.wg.Wait()
if m.eventChan != nil {
close(m.eventChan)
m.eventChan = nil
}
if m.errorChan != nil {
close(m.errorChan)
m.errorChan = nil
}
return nil
}
// ErrorChan returns the plugin's error channel
func (m *Mempool) ErrorChan() <-chan error {
return m.errorChan
}
// InputChan returns nil (mempool is an input-only plugin)
func (m *Mempool) InputChan() chan<- event.Event {
return nil
}
// OutputChan returns the channel of mempool transaction events
func (m *Mempool) OutputChan() <-chan event.Event {
return m.eventChan
}
func (m *Mempool) setupConnection() error {
if m.network != "" {
network, ok := ouroboros.NetworkByName(m.network)
if !ok {
return fmt.Errorf("unknown network: %s", m.network)
}
if m.networkMagic == 0 {
m.networkMagic = network.NetworkMagic
}
}
if m.address != "" {
m.dialFamily = "tcp"
m.dialAddress = m.address
if !m.ntcTcp {
return errors.New("address requires input-mempool-ntc-tcp=true for NtC over TCP")
}
} else if m.socketPath != "" {
m.dialFamily = "unix"
m.dialAddress = m.socketPath
} else {
return errors.New("must specify input-mempool-socket-path or input-mempool-address")
}
if m.networkMagic == 0 {
return errors.New("must specify input-mempool-network or input-mempool-network-magic")
}
m.pollInterval = defaultPollInterval
if m.pollIntervalStr != "" {
d, err := time.ParseDuration(m.pollIntervalStr)
if err != nil {
return fmt.Errorf("invalid poll interval: %w", err)
}
if d <= 0 {
return errors.New("poll interval must be positive")
}
m.pollInterval = d
}
cfg := localtxmonitor.NewConfig(
localtxmonitor.WithAcquireTimeout(10*time.Second),
localtxmonitor.WithQueryTimeout(30*time.Second),
)
oConn, err := ouroboros.NewConnection(
ouroboros.WithNetworkMagic(m.networkMagic),
ouroboros.WithNodeToNode(false),
ouroboros.WithKeepAlive(true),
ouroboros.WithLocalTxMonitorConfig(cfg),
)
if err != nil {
return err
}
if err := oConn.Dial(m.dialFamily, m.dialAddress); err != nil {
_ = oConn.Close()
return err
}
m.oConn = oConn
if m.logger != nil {
m.logger.Info("connected to node for mempool", "address", m.dialAddress)
}
m.wg.Add(1)
go func() {
defer m.wg.Done()
for {
select {
case <-m.doneChan:
return
case err, ok := <-m.oConn.ErrorChan():
if !ok {
return
}
select {
case <-m.doneChan:
return
case m.errorChan <- err:
}
}
}
}()
return nil
}
func (m *Mempool) pollLoop() {
defer m.wg.Done()
if m.pollInterval <= 0 {
m.pollInterval = defaultPollInterval
}
ticker := time.NewTicker(m.pollInterval)
defer ticker.Stop()
for {
select {
case <-m.doneChan:
return
case <-ticker.C:
m.pollOnce()
}
}
}
func (m *Mempool) pollOnce() {
if m.oConn == nil {
return
}
client := m.oConn.LocalTxMonitor().Client
if client == nil {
return
}
if err := client.Acquire(); err != nil {
if m.logger != nil {
m.logger.Warn("mempool acquire failed", "error", err)
}
return
}
defer func() {
_ = client.Release()
}()
_, _, numTxs, err := client.GetSizes()
if err != nil {
if m.logger != nil {
m.logger.Warn("mempool GetSizes failed", "error", err)
}
return
}
if numTxs == 0 {
return
}
if m.seenTxHashes == nil {
m.seenTxHashes = make(map[string]struct{})
}
// Collect all txs this poll. We only need to remember last poll's hashes
// to emit events only for newly seen transactions.
type pollTx struct {
hash string
tx ledger.Transaction
}
var pollTxs []pollTx
for {
select {
case <-m.doneChan:
return
default:
}
txCbor, err := client.NextTx()
if err != nil {
if m.logger != nil {
m.logger.Warn("mempool NextTx failed", "error", err)
}
return
}
if len(txCbor) == 0 {
break
}
tx, err := m.parseTx(txCbor)
if err != nil {
if m.logger != nil {
m.logger.Debug("mempool skip tx parse error", "error", err, "cbor_len", len(txCbor))
}
continue
}
txHash := tx.Hash().String()
pollTxs = append(pollTxs, pollTx{hash: txHash, tx: tx})
}
thisPollHashes := make(map[string]struct{}, len(pollTxs))
for _, p := range pollTxs {
thisPollHashes[p.hash] = struct{}{}
}
for _, p := range pollTxs {
if _, seen := m.seenTxHashes[p.hash]; seen {
continue
}
ctx := event.NewMempoolTransactionContext(p.tx, 0, m.networkMagic)
payload := event.NewTransactionEventFromTx(p.tx, m.includeCbor)
evt := event.New("mempool.transaction", time.Now(), ctx, payload)
select {
case <-m.doneChan:
return
case m.eventChan <- evt:
}
}
// Remember only this poll's hashes for next time (no unbounded growth).
m.seenTxHashes = thisPollHashes
}
func (m *Mempool) parseTx(data []byte) (ledger.Transaction, error) {
txType, err := ledger.DetermineTransactionType(data)
if err != nil {
return nil, err
}
return ledger.NewTransactionFromCbor(txType, data)
}