forked from ltcsuite/ltcwallet
/
bitcoind_rpc_events.go
305 lines (248 loc) · 8.28 KB
/
bitcoind_rpc_events.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
package chain
import (
"math/rand"
"sync"
"time"
"github.com/ltcsuite/ltcd/chaincfg/chainhash"
"github.com/ltcsuite/ltcd/rpcclient"
"github.com/ltcsuite/ltcd/wire"
)
const (
// defaultBlockPollInterval is the default interval used for querying
// for new blocks.
defaultBlockPollInterval = time.Second * 10
// defaultTxPollInterval is the default interval used for querying for
// new mempool transactions.
defaultTxPollInterval = time.Second * 60
)
// PollingConfig holds all the config options used for setting up
// bitcoindRPCPollingEvents.
type PollingConfig struct {
// BlockPollingInterval is the interval that will be used to poll
// bitcoind for new blocks.
BlockPollingInterval time.Duration
// TxPollingInterval is the interval that will be used to poll bitcoind
// for new transactions. If a jitter factor is configed, it will be
// applied to this value to provide randomness in the range,
// - max: TxPollingInterval * (1 + TxPollingIntervalJitter)
// - min: TxPollingInterval * (1 - TxPollingIntervalJitter)
TxPollingInterval time.Duration
// TxPollingIntervalScale defines a factor that's used to simulates
// jitter by scaling TxPollingInterval with it. This value must be no
// less than 0. Default to 0, meaning no jitter will be applied.
TxPollingIntervalJitter float64
// RPCBatchSize defines the number of RPC requests to be batches before
// sending them to the bitcoind node.
RPCBatchSize uint32
// RPCBatchInterval defines the time to wait before attempting the next
// batch when the current one finishes.
RPCBatchInterval time.Duration
}
// bitcoindRPCPollingEvents delivers block and transaction notifications that
// it gets by polling bitcoind's rpc interface at regular intervals.
type bitcoindRPCPollingEvents struct {
cfg *PollingConfig
client *rpcclient.Client
// mempool holds all the transactions that we currently see as being in
// the mempool. This is used so that we know which transactions we have
// already sent notifications for.
mempool *mempool
// blockNtfns is a channel to which any new blocks will be sent.
blockNtfns chan *wire.MsgBlock
// txNtfns is a channel to which any new transactions will be sent.
txNtfns chan *wire.MsgTx
wg sync.WaitGroup
quit chan struct{}
}
// Ensure bitcoindRPCPollingEvents implements the BitcoinEvents interface at
// compile time.
var _ BitcoindEvents = (*bitcoindRPCPollingEvents)(nil)
// newBitcoindRPCPollingEvents instantiates a new bitcoindRPCPollingEvents
// object.
func newBitcoindRPCPollingEvents(cfg *PollingConfig, client *rpcclient.Client,
bClient batchClient, hasRPC bool) *bitcoindRPCPollingEvents {
if cfg.BlockPollingInterval == 0 {
cfg.BlockPollingInterval = defaultBlockPollInterval
}
if cfg.TxPollingInterval == 0 {
cfg.TxPollingInterval = defaultTxPollInterval
}
// Floor the jitter value to be 0.
if cfg.TxPollingIntervalJitter < 0 {
log.Warnf("Jitter value(%v) must be positive, setting to 0",
cfg.TxPollingIntervalJitter)
cfg.TxPollingIntervalJitter = 0
}
// Create the config for mempool and attach default values if not
// configed.
mCfg := &mempoolConfig{
client: bClient,
getRawTxBatchSize: cfg.RPCBatchSize,
batchWaitInterval: cfg.RPCBatchInterval,
hasPrevoutRPC: hasRPC,
}
if cfg.RPCBatchSize == 0 {
mCfg.getRawTxBatchSize = DefaultGetRawTxBatchSize
}
if cfg.RPCBatchInterval == 0 {
mCfg.batchWaitInterval = DefaultBatchWaitInterval
}
return &bitcoindRPCPollingEvents{
cfg: cfg,
client: client,
txNtfns: make(chan *wire.MsgTx),
blockNtfns: make(chan *wire.MsgBlock),
mempool: newMempool(mCfg),
quit: make(chan struct{}),
}
}
// Start kicks off all the bitcoindRPCPollingEvents goroutines.
func (b *bitcoindRPCPollingEvents) Start() error {
info, err := b.client.GetBlockChainInfo()
if err != nil {
return err
}
// Load the mempool so we don't miss transactions.
if err := b.mempool.LoadMempool(); err != nil {
return err
}
b.wg.Add(2)
go b.blockEventHandlerRPC(info.Blocks)
go b.txEventHandlerRPC()
return nil
}
// Stop cleans up all the bitcoindRPCPollingEvents resources and goroutines.
func (b *bitcoindRPCPollingEvents) Stop() error {
b.mempool.Shutdown()
close(b.quit)
b.wg.Wait()
return nil
}
// TxNotifications returns a channel which will deliver new transactions.
func (b *bitcoindRPCPollingEvents) TxNotifications() <-chan *wire.MsgTx {
return b.txNtfns
}
// BlockNotifications returns a channel which will deliver new blocks.
func (b *bitcoindRPCPollingEvents) BlockNotifications() <-chan *wire.MsgBlock {
return b.blockNtfns
}
// LookupInputSpend returns the transaction that spends the given outpoint
// found in the mempool.
func (b *bitcoindRPCPollingEvents) LookupInputSpend(
op wire.OutPoint) (chainhash.Hash, bool) {
b.mempool.RLock()
defer b.mempool.RUnlock()
// If `gettxspendingprevout` is not supported, we need to loop it up in
// our local mempool.
if !b.mempool.cfg.hasPrevoutRPC {
// Check whether the input is in mempool.
return b.mempool.containsInput(op)
}
// Otherwise, we can use the `gettxspendingprevout` RPC to look up the
// input.
return getTxSpendingPrevOut(op, b.client)
}
// blockEventHandlerRPC is a goroutine that uses the rpc client to check if we
// have a new block every so often.
func (b *bitcoindRPCPollingEvents) blockEventHandlerRPC(startHeight int32) {
defer b.wg.Done()
ticker := time.NewTicker(b.cfg.BlockPollingInterval)
defer ticker.Stop()
height := startHeight
log.Infof("Started polling for new bitcoind blocks via RPC at "+
"height %d", height)
for {
select {
case <-ticker.C:
// At every interval, we poll to see if there's a block
// with a height that exceeds the height that we
// previously recorded.
info, err := b.client.GetBlockChainInfo()
if err != nil {
log.Errorf("Unable to retrieve best block: "+
"%v", err)
continue
}
// If the block isn't new, we continue and wait for the
// next interval tick. In order to replicate the
// behaviour of the zmq block subscription, we only do
// a height based check here. We only deliver
// notifications if the new block has a height above the
// one we previously saw. The caller is left to
// determine if there has been a reorg.
if info.Blocks <= height {
continue
}
// Since we do a height based check, we send
// notifications for each block with a height between
// the last height we recorded and the new height.
for i := height + 1; i <= info.Blocks; i++ {
newHash, err := b.client.GetBlockHash(int64(i))
if err != nil {
log.Errorf("Unable to retrieve "+
"block hash: %v", err)
continue
}
newBlock, err := b.client.GetBlock(newHash)
if err != nil {
log.Errorf("Unable to retrieve "+
"block: %v", err)
continue
}
// notify the client of the new block.
select {
case b.blockNtfns <- newBlock:
case <-b.quit:
return
}
// From our local mempool map, let's remove each
// of the transactions that are confirmed in
// this new block, since they are no longer in
// the mempool.
b.mempool.Clean(newBlock.Transactions)
height++
}
case <-b.quit:
return
}
}
}
// txEventHandlerRPC is a goroutine that uses the RPC client to check the
// mempool for new transactions.
func (b *bitcoindRPCPollingEvents) txEventHandlerRPC() {
defer b.wg.Done()
// We'll wait to start the main reconciliation loop until we're doing
// the initial mempool load.
b.mempool.WaitForInit()
log.Info("Started polling mempool for new bitcoind transactions via RPC.")
// Create a ticker that fires randomly.
rand.Seed(time.Now().UnixNano())
ticker := NewJitterTicker(
b.cfg.TxPollingInterval, b.cfg.TxPollingIntervalJitter,
)
defer ticker.Stop()
for {
select {
case <-ticker.C:
log.Tracef("Reconciling mempool spends with node " +
"mempool...")
now := time.Now()
// After each ticker interval, we poll the mempool to
// check for transactions we haven't seen yet and
// update our local mempool with the new mempool.
newTxs := b.mempool.UpdateMempoolTxes()
log.Tracef("Reconciled mempool spends in %v",
time.Since(now))
// Notify the client of each new transaction.
for _, tx := range newTxs {
select {
case b.txNtfns <- tx:
case <-b.quit:
return
}
}
case <-b.quit:
return
}
}
}