• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lightningnetwork / lnd / 15155511119

21 May 2025 06:52AM UTC coverage: 57.389% (-11.6%) from 68.996%
15155511119

Pull #9844

github

web-flow
Merge 8658c8597 into c52a6ddeb
Pull Request #9844: Refactor Payment PR 3

346 of 493 new or added lines in 4 files covered. (70.18%)

30172 existing lines in 456 files now uncovered.

95441 of 166305 relevant lines covered (57.39%)

0.61 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/chainntnfs/bitcoindnotify/bitcoind.go
1
package bitcoindnotify
2

3
import (
4
        "errors"
5
        "fmt"
6
        "sync"
7
        "sync/atomic"
8

9
        "github.com/btcsuite/btcd/btcjson"
10
        "github.com/btcsuite/btcd/btcutil"
11
        "github.com/btcsuite/btcd/chaincfg"
12
        "github.com/btcsuite/btcd/chaincfg/chainhash"
13
        "github.com/btcsuite/btcd/txscript"
14
        "github.com/btcsuite/btcd/wire"
15
        "github.com/btcsuite/btcwallet/chain"
16
        "github.com/lightningnetwork/lnd/blockcache"
17
        "github.com/lightningnetwork/lnd/chainntnfs"
18
        "github.com/lightningnetwork/lnd/fn/v2"
19
        "github.com/lightningnetwork/lnd/queue"
20
)
21

22
const (
23
        // notifierType uniquely identifies a concrete implementation of the
24
        // ChainNotifier interface that makes use of the bitcoind ZMQ interface.
25
        notifierTypeZMQ = "bitcoind"
26

27
        // notifierTypeRPCPolling uniquely identifies a concrete implementation
28
        // of the ChainNotifier interface that makes use of the bitcoind RPC
29
        // interface.
30
        notifierTypeRPCPolling = "bitcoind-rpc-polling"
31
)
32

33
// TODO(roasbeef): generalize struct below:
34
//  * move chans to config
35
//  * extract common code
36
//  * allow outside callers to handle send conditions
37

38
// BitcoindNotifier implements the ChainNotifier interface using a bitcoind
39
// chain client. Multiple concurrent clients are supported. All notifications
40
// are achieved via non-blocking sends on client channels.
41
type BitcoindNotifier struct {
42
        epochClientCounter uint64 // To be used atomically.
43

44
        start   sync.Once
45
        active  int32 // To be used atomically.
46
        stopped int32 // To be used atomically.
47

48
        chainConn   *chain.BitcoindClient
49
        chainParams *chaincfg.Params
50

51
        notificationCancels  chan interface{}
52
        notificationRegistry chan interface{}
53

54
        txNotifier *chainntnfs.TxNotifier
55

56
        blockEpochClients map[uint64]*blockEpochRegistration
57

58
        bestBlock chainntnfs.BlockEpoch
59

60
        // blockCache is a LRU block cache.
61
        blockCache *blockcache.BlockCache
62

63
        // spendHintCache is a cache used to query and update the latest height
64
        // hints for an outpoint. Each height hint represents the earliest
65
        // height at which the outpoint could have been spent within the chain.
66
        spendHintCache chainntnfs.SpendHintCache
67

68
        // confirmHintCache is a cache used to query the latest height hints for
69
        // a transaction. Each height hint represents the earliest height at
70
        // which the transaction could have confirmed within the chain.
71
        confirmHintCache chainntnfs.ConfirmHintCache
72

73
        // memNotifier notifies clients of events related to the mempool.
74
        memNotifier *chainntnfs.MempoolNotifier
75

76
        wg   sync.WaitGroup
77
        quit chan struct{}
78
}
79

80
// Ensure BitcoindNotifier implements the ChainNotifier interface at compile
81
// time.
82
var _ chainntnfs.ChainNotifier = (*BitcoindNotifier)(nil)
83

84
// Ensure BitcoindNotifier implements the MempoolWatcher interface at compile
85
// time.
86
var _ chainntnfs.MempoolWatcher = (*BitcoindNotifier)(nil)
87

88
// New returns a new BitcoindNotifier instance. This function assumes the
89
// bitcoind node detailed in the passed configuration is already running, and
90
// willing to accept RPC requests and new zmq clients.
91
func New(chainConn *chain.BitcoindConn, chainParams *chaincfg.Params,
92
        spendHintCache chainntnfs.SpendHintCache,
93
        confirmHintCache chainntnfs.ConfirmHintCache,
UNCOV
94
        blockCache *blockcache.BlockCache) *BitcoindNotifier {
×
UNCOV
95

×
UNCOV
96
        notifier := &BitcoindNotifier{
×
UNCOV
97
                chainParams: chainParams,
×
UNCOV
98

×
UNCOV
99
                notificationCancels:  make(chan interface{}),
×
UNCOV
100
                notificationRegistry: make(chan interface{}),
×
UNCOV
101

×
UNCOV
102
                blockEpochClients: make(map[uint64]*blockEpochRegistration),
×
UNCOV
103

×
UNCOV
104
                spendHintCache:   spendHintCache,
×
UNCOV
105
                confirmHintCache: confirmHintCache,
×
UNCOV
106

×
UNCOV
107
                blockCache:  blockCache,
×
UNCOV
108
                memNotifier: chainntnfs.NewMempoolNotifier(),
×
UNCOV
109

×
UNCOV
110
                quit: make(chan struct{}),
×
UNCOV
111
        }
×
UNCOV
112

×
UNCOV
113
        notifier.chainConn = chainConn.NewBitcoindClient()
×
UNCOV
114

×
UNCOV
115
        return notifier
×
UNCOV
116
}
×
117

118
// Start connects to the running bitcoind node over websockets, registers for
119
// block notifications, and finally launches all related helper goroutines.
UNCOV
120
func (b *BitcoindNotifier) Start() error {
×
UNCOV
121
        var startErr error
×
UNCOV
122
        b.start.Do(func() {
×
UNCOV
123
                startErr = b.startNotifier()
×
UNCOV
124
        })
×
125

UNCOV
126
        return startErr
×
127
}
128

129
// Stop shutsdown the BitcoindNotifier.
UNCOV
130
func (b *BitcoindNotifier) Stop() error {
×
UNCOV
131
        // Already shutting down?
×
UNCOV
132
        if atomic.AddInt32(&b.stopped, 1) != 1 {
×
133
                return nil
×
134
        }
×
135

UNCOV
136
        chainntnfs.Log.Info("bitcoind notifier shutting down...")
×
UNCOV
137
        defer chainntnfs.Log.Debug("bitcoind notifier shutdown complete")
×
UNCOV
138

×
UNCOV
139
        // Shutdown the rpc client, this gracefully disconnects from bitcoind,
×
UNCOV
140
        // and cleans up all related resources.
×
UNCOV
141
        b.chainConn.Stop()
×
UNCOV
142
        b.chainConn.WaitForShutdown()
×
UNCOV
143

×
UNCOV
144
        close(b.quit)
×
UNCOV
145
        b.wg.Wait()
×
UNCOV
146

×
UNCOV
147
        // Notify all pending clients of our shutdown by closing the related
×
UNCOV
148
        // notification channels.
×
UNCOV
149
        for _, epochClient := range b.blockEpochClients {
×
UNCOV
150
                close(epochClient.cancelChan)
×
UNCOV
151
                epochClient.wg.Wait()
×
UNCOV
152

×
UNCOV
153
                close(epochClient.epochChan)
×
UNCOV
154
        }
×
155

156
        // The txNotifier is only initialized in the start method therefore we
157
        // need to make sure we don't access a nil pointer here.
UNCOV
158
        if b.txNotifier != nil {
×
UNCOV
159
                b.txNotifier.TearDown()
×
UNCOV
160
        }
×
161

162
        // Stop the mempool notifier.
UNCOV
163
        b.memNotifier.TearDown()
×
UNCOV
164

×
UNCOV
165
        return nil
×
166
}
167

168
// Started returns true if this instance has been started, and false otherwise.
UNCOV
169
func (b *BitcoindNotifier) Started() bool {
×
UNCOV
170
        return atomic.LoadInt32(&b.active) != 0
×
UNCOV
171
}
×
172

UNCOV
173
func (b *BitcoindNotifier) startNotifier() error {
×
UNCOV
174
        chainntnfs.Log.Infof("bitcoind notifier starting...")
×
UNCOV
175

×
UNCOV
176
        // Connect to bitcoind, and register for notifications on connected,
×
UNCOV
177
        // and disconnected blocks.
×
UNCOV
178
        if err := b.chainConn.Start(); err != nil {
×
179
                return err
×
180
        }
×
UNCOV
181
        if err := b.chainConn.NotifyBlocks(); err != nil {
×
182
                return err
×
183
        }
×
184

UNCOV
185
        currentHash, currentHeight, err := b.chainConn.GetBestBlock()
×
UNCOV
186
        if err != nil {
×
187
                return err
×
188
        }
×
UNCOV
189
        blockHeader, err := b.chainConn.GetBlockHeader(currentHash)
×
UNCOV
190
        if err != nil {
×
191
                return err
×
192
        }
×
193

UNCOV
194
        b.txNotifier = chainntnfs.NewTxNotifier(
×
UNCOV
195
                uint32(currentHeight), chainntnfs.ReorgSafetyLimit,
×
UNCOV
196
                b.confirmHintCache, b.spendHintCache,
×
UNCOV
197
        )
×
UNCOV
198

×
UNCOV
199
        b.bestBlock = chainntnfs.BlockEpoch{
×
UNCOV
200
                Height:      currentHeight,
×
UNCOV
201
                Hash:        currentHash,
×
UNCOV
202
                BlockHeader: blockHeader,
×
UNCOV
203
        }
×
UNCOV
204

×
UNCOV
205
        b.wg.Add(1)
×
UNCOV
206
        go b.notificationDispatcher()
×
UNCOV
207

×
UNCOV
208
        // Set the active flag now that we've completed the full
×
UNCOV
209
        // startup.
×
UNCOV
210
        atomic.StoreInt32(&b.active, 1)
×
UNCOV
211

×
UNCOV
212
        chainntnfs.Log.Debugf("bitcoind notifier started")
×
UNCOV
213

×
UNCOV
214
        return nil
×
215
}
216

217
// notificationDispatcher is the primary goroutine which handles client
218
// notification registrations, as well as notification dispatches.
UNCOV
219
func (b *BitcoindNotifier) notificationDispatcher() {
×
UNCOV
220
        defer b.wg.Done()
×
UNCOV
221

×
UNCOV
222
out:
×
UNCOV
223
        for {
×
UNCOV
224
                select {
×
UNCOV
225
                case cancelMsg := <-b.notificationCancels:
×
UNCOV
226
                        switch msg := cancelMsg.(type) {
×
UNCOV
227
                        case *epochCancel:
×
UNCOV
228
                                chainntnfs.Log.Infof("Cancelling epoch "+
×
UNCOV
229
                                        "notification, epoch_id=%v", msg.epochID)
×
UNCOV
230

×
UNCOV
231
                                // First, we'll lookup the original
×
UNCOV
232
                                // registration in order to stop the active
×
UNCOV
233
                                // queue goroutine.
×
UNCOV
234
                                reg := b.blockEpochClients[msg.epochID]
×
UNCOV
235
                                reg.epochQueue.Stop()
×
UNCOV
236

×
UNCOV
237
                                // Next, close the cancel channel for this
×
UNCOV
238
                                // specific client, and wait for the client to
×
UNCOV
239
                                // exit.
×
UNCOV
240
                                close(b.blockEpochClients[msg.epochID].cancelChan)
×
UNCOV
241
                                b.blockEpochClients[msg.epochID].wg.Wait()
×
UNCOV
242

×
UNCOV
243
                                // Once the client has exited, we can then
×
UNCOV
244
                                // safely close the channel used to send epoch
×
UNCOV
245
                                // notifications, in order to notify any
×
UNCOV
246
                                // listeners that the intent has been
×
UNCOV
247
                                // canceled.
×
UNCOV
248
                                close(b.blockEpochClients[msg.epochID].epochChan)
×
UNCOV
249
                                delete(b.blockEpochClients, msg.epochID)
×
250

251
                        }
UNCOV
252
                case registerMsg := <-b.notificationRegistry:
×
UNCOV
253
                        switch msg := registerMsg.(type) {
×
UNCOV
254
                        case *chainntnfs.HistoricalConfDispatch:
×
UNCOV
255
                                // Look up whether the transaction is already
×
UNCOV
256
                                // included in the active chain. We'll do this
×
UNCOV
257
                                // in a goroutine to prevent blocking
×
UNCOV
258
                                // potentially long rescans.
×
UNCOV
259
                                //
×
UNCOV
260
                                // TODO(wilmer): add retry logic if rescan fails?
×
UNCOV
261
                                b.wg.Add(1)
×
UNCOV
262

×
UNCOV
263
                                //nolint:ll
×
UNCOV
264
                                go func(msg *chainntnfs.HistoricalConfDispatch) {
×
UNCOV
265
                                        defer b.wg.Done()
×
UNCOV
266

×
UNCOV
267
                                        confDetails, _, err := b.historicalConfDetails(
×
UNCOV
268
                                                msg.ConfRequest,
×
UNCOV
269
                                                msg.StartHeight, msg.EndHeight,
×
UNCOV
270
                                        )
×
UNCOV
271
                                        if err != nil {
×
272
                                                chainntnfs.Log.Errorf("Rescan to "+
×
273
                                                        "determine the conf "+
×
274
                                                        "details of %v within "+
×
275
                                                        "range %d-%d failed: %v",
×
276
                                                        msg.ConfRequest,
×
277
                                                        msg.StartHeight,
×
278
                                                        msg.EndHeight, err)
×
279
                                                return
×
280
                                        }
×
281

282
                                        // If the historical dispatch finished
283
                                        // without error, we will invoke
284
                                        // UpdateConfDetails even if none were
285
                                        // found. This allows the notifier to
286
                                        // begin safely updating the height hint
287
                                        // cache at tip, since any pending
288
                                        // rescans have now completed.
UNCOV
289
                                        err = b.txNotifier.UpdateConfDetails(
×
UNCOV
290
                                                msg.ConfRequest, confDetails,
×
UNCOV
291
                                        )
×
UNCOV
292
                                        if err != nil {
×
293
                                                chainntnfs.Log.Errorf("Unable "+
×
294
                                                        "to update conf "+
×
295
                                                        "details of %v: %v",
×
296
                                                        msg.ConfRequest, err)
×
297
                                        }
×
298
                                }(msg)
299

UNCOV
300
                        case *chainntnfs.HistoricalSpendDispatch:
×
UNCOV
301
                                // In order to ensure we don't block the caller
×
UNCOV
302
                                // on what may be a long rescan, we'll launch a
×
UNCOV
303
                                // goroutine to do so in the background.
×
UNCOV
304
                                //
×
UNCOV
305
                                // TODO(wilmer): add retry logic if rescan fails?
×
UNCOV
306
                                b.wg.Add(1)
×
UNCOV
307

×
UNCOV
308
                                //nolint:ll
×
UNCOV
309
                                go func(msg *chainntnfs.HistoricalSpendDispatch) {
×
UNCOV
310
                                        defer b.wg.Done()
×
UNCOV
311

×
UNCOV
312
                                        spendDetails, err := b.historicalSpendDetails(
×
UNCOV
313
                                                msg.SpendRequest,
×
UNCOV
314
                                                msg.StartHeight, msg.EndHeight,
×
UNCOV
315
                                        )
×
UNCOV
316
                                        if err != nil {
×
317
                                                chainntnfs.Log.Errorf("Rescan to "+
×
318
                                                        "determine the spend "+
×
319
                                                        "details of %v within "+
×
320
                                                        "range %d-%d failed: %v",
×
321
                                                        msg.SpendRequest,
×
322
                                                        msg.StartHeight,
×
323
                                                        msg.EndHeight, err)
×
324
                                                return
×
325
                                        }
×
326

UNCOV
327
                                        chainntnfs.Log.Infof("Historical "+
×
UNCOV
328
                                                "spend dispatch finished "+
×
UNCOV
329
                                                "for request %v (start=%v "+
×
UNCOV
330
                                                "end=%v) with details: %v",
×
UNCOV
331
                                                msg.SpendRequest,
×
UNCOV
332
                                                msg.StartHeight, msg.EndHeight,
×
UNCOV
333
                                                spendDetails)
×
UNCOV
334

×
UNCOV
335
                                        // If the historical dispatch finished
×
UNCOV
336
                                        // without error, we will invoke
×
UNCOV
337
                                        // UpdateSpendDetails even if none were
×
UNCOV
338
                                        // found. This allows the notifier to
×
UNCOV
339
                                        // begin safely updating the height hint
×
UNCOV
340
                                        // cache at tip, since any pending
×
UNCOV
341
                                        // rescans have now completed.
×
UNCOV
342
                                        err = b.txNotifier.UpdateSpendDetails(
×
UNCOV
343
                                                msg.SpendRequest, spendDetails,
×
UNCOV
344
                                        )
×
UNCOV
345
                                        if err != nil {
×
346
                                                chainntnfs.Log.Errorf("Unable "+
×
347
                                                        "to update spend "+
×
348
                                                        "details of %v: %v",
×
349
                                                        msg.SpendRequest, err)
×
350
                                        }
×
351
                                }(msg)
352

UNCOV
353
                        case *blockEpochRegistration:
×
UNCOV
354
                                chainntnfs.Log.Infof("New block epoch subscription")
×
UNCOV
355

×
UNCOV
356
                                b.blockEpochClients[msg.epochID] = msg
×
UNCOV
357

×
UNCOV
358
                                // If the client did not provide their best
×
UNCOV
359
                                // known block, then we'll immediately dispatch
×
UNCOV
360
                                // a notification for the current tip.
×
UNCOV
361
                                if msg.bestBlock == nil {
×
UNCOV
362
                                        b.notifyBlockEpochClient(
×
UNCOV
363
                                                msg, b.bestBlock.Height,
×
UNCOV
364
                                                b.bestBlock.Hash,
×
UNCOV
365
                                                b.bestBlock.BlockHeader,
×
UNCOV
366
                                        )
×
UNCOV
367

×
UNCOV
368
                                        msg.errorChan <- nil
×
UNCOV
369
                                        continue
×
370
                                }
371

372
                                // Otherwise, we'll attempt to deliver the
373
                                // backlog of notifications from their best
374
                                // known block.
UNCOV
375
                                missedBlocks, err := chainntnfs.GetClientMissedBlocks(
×
UNCOV
376
                                        b.chainConn, msg.bestBlock,
×
UNCOV
377
                                        b.bestBlock.Height, true,
×
UNCOV
378
                                )
×
UNCOV
379
                                if err != nil {
×
UNCOV
380
                                        msg.errorChan <- err
×
UNCOV
381
                                        continue
×
382
                                }
383

UNCOV
384
                                for _, block := range missedBlocks {
×
UNCOV
385
                                        b.notifyBlockEpochClient(
×
UNCOV
386
                                                msg, block.Height, block.Hash,
×
UNCOV
387
                                                block.BlockHeader,
×
UNCOV
388
                                        )
×
UNCOV
389
                                }
×
390

UNCOV
391
                                msg.errorChan <- nil
×
392
                        }
393

UNCOV
394
                case ntfn := <-b.chainConn.Notifications():
×
UNCOV
395
                        switch item := ntfn.(type) {
×
UNCOV
396
                        case chain.BlockConnected:
×
UNCOV
397
                                blockHeader, err :=
×
UNCOV
398
                                        b.chainConn.GetBlockHeader(&item.Hash)
×
UNCOV
399
                                if err != nil {
×
400
                                        chainntnfs.Log.Errorf("Unable to fetch "+
×
401
                                                "block header: %v", err)
×
402
                                        continue
×
403
                                }
404

UNCOV
405
                                if blockHeader.PrevBlock != *b.bestBlock.Hash {
×
UNCOV
406
                                        // Handle the case where the notifier
×
UNCOV
407
                                        // missed some blocks from its chain
×
UNCOV
408
                                        // backend.
×
UNCOV
409
                                        chainntnfs.Log.Infof("Missed blocks, " +
×
UNCOV
410
                                                "attempting to catch up")
×
UNCOV
411
                                        newBestBlock, missedBlocks, err :=
×
UNCOV
412
                                                chainntnfs.HandleMissedBlocks(
×
UNCOV
413
                                                        b.chainConn,
×
UNCOV
414
                                                        b.txNotifier,
×
UNCOV
415
                                                        b.bestBlock, item.Height,
×
UNCOV
416
                                                        true,
×
UNCOV
417
                                                )
×
UNCOV
418

×
UNCOV
419
                                        if err != nil {
×
420
                                                // Set the bestBlock here in case
×
421
                                                // a catch up partially completed.
×
422
                                                b.bestBlock = newBestBlock
×
423
                                                chainntnfs.Log.Error(err)
×
424
                                                continue
×
425
                                        }
426

UNCOV
427
                                        for _, block := range missedBlocks {
×
UNCOV
428
                                                err := b.handleBlockConnected(block)
×
UNCOV
429
                                                if err != nil {
×
430
                                                        chainntnfs.Log.Error(err)
×
431
                                                        continue out
×
432
                                                }
433
                                        }
434
                                }
435

UNCOV
436
                                newBlock := chainntnfs.BlockEpoch{
×
UNCOV
437
                                        Height:      item.Height,
×
UNCOV
438
                                        Hash:        &item.Hash,
×
UNCOV
439
                                        BlockHeader: blockHeader,
×
UNCOV
440
                                }
×
UNCOV
441
                                if err := b.handleBlockConnected(newBlock); err != nil {
×
442
                                        chainntnfs.Log.Error(err)
×
443
                                }
×
444

UNCOV
445
                                continue
×
446

UNCOV
447
                        case chain.BlockDisconnected:
×
UNCOV
448
                                if item.Height != b.bestBlock.Height {
×
449
                                        chainntnfs.Log.Infof("Missed disconnected" +
×
450
                                                "blocks, attempting to catch up")
×
451
                                }
×
452

UNCOV
453
                                newBestBlock, err := chainntnfs.RewindChain(
×
UNCOV
454
                                        b.chainConn, b.txNotifier,
×
UNCOV
455
                                        b.bestBlock, item.Height-1,
×
UNCOV
456
                                )
×
UNCOV
457
                                if err != nil {
×
458
                                        chainntnfs.Log.Errorf("Unable to rewind chain "+
×
459
                                                "from height %d to height %d: %v",
×
460
                                                b.bestBlock.Height, item.Height-1, err)
×
461
                                }
×
462

463
                                // Set the bestBlock here in case a chain
464
                                // rewind partially completed.
UNCOV
465
                                b.bestBlock = newBestBlock
×
466

UNCOV
467
                        case chain.RelevantTx:
×
UNCOV
468
                                tx := btcutil.NewTx(&item.TxRecord.MsgTx)
×
UNCOV
469

×
UNCOV
470
                                // Init values.
×
UNCOV
471
                                isMempool := false
×
UNCOV
472
                                height := uint32(0)
×
UNCOV
473

×
UNCOV
474
                                // Unwrap values.
×
UNCOV
475
                                if item.Block == nil {
×
UNCOV
476
                                        isMempool = true
×
UNCOV
477
                                } else {
×
UNCOV
478
                                        height = uint32(item.Block.Height)
×
UNCOV
479
                                }
×
480

481
                                // Handle the transaction.
UNCOV
482
                                b.handleRelevantTx(tx, isMempool, height)
×
483
                        }
484

UNCOV
485
                case <-b.quit:
×
UNCOV
486
                        break out
×
487
                }
488
        }
489
}
490

491
// handleRelevantTx handles a new transaction that has been seen either in a
492
// block or in the mempool. If in mempool, it will ask the mempool notifier to
493
// handle it. If in a block, it will ask the txNotifier to handle it, and
494
// cancel any relevant subscriptions made in the mempool.
495
func (b *BitcoindNotifier) handleRelevantTx(tx *btcutil.Tx,
UNCOV
496
        mempool bool, height uint32) {
×
UNCOV
497

×
UNCOV
498
        // If this is a mempool spend, we'll ask the mempool notifier to handle
×
UNCOV
499
        // it.
×
UNCOV
500
        if mempool {
×
UNCOV
501
                err := b.memNotifier.ProcessRelevantSpendTx(tx)
×
UNCOV
502
                if err != nil {
×
503
                        chainntnfs.Log.Errorf("Unable to process transaction "+
×
504
                                "%v: %v", tx.Hash(), err)
×
505
                }
×
506

UNCOV
507
                return
×
508
        }
509

510
        // Otherwise this is a confirmed spend, and we'll ask the tx notifier
511
        // to handle it.
UNCOV
512
        err := b.txNotifier.ProcessRelevantSpendTx(tx, height)
×
UNCOV
513
        if err != nil {
×
514
                chainntnfs.Log.Errorf("Unable to process transaction %v: %v",
×
515
                        tx.Hash(), err)
×
516

×
517
                return
×
518
        }
×
519

520
        // Once the tx is processed, we will ask the memNotifier to unsubscribe
521
        // the input.
522
        //
523
        // NOTE(yy): we could build it into txNotifier.ProcessRelevantSpendTx,
524
        // but choose to implement it here so we can easily decouple the two
525
        // notifiers in the future.
UNCOV
526
        b.memNotifier.UnsubsribeConfirmedSpentTx(tx)
×
527
}
528

529
// historicalConfDetails looks up whether a confirmation request (txid/output
530
// script) has already been included in a block in the active chain and, if so,
531
// returns details about said block.
532
func (b *BitcoindNotifier) historicalConfDetails(confRequest chainntnfs.ConfRequest,
533
        startHeight, endHeight uint32) (*chainntnfs.TxConfirmation,
UNCOV
534
        chainntnfs.TxConfStatus, error) {
×
UNCOV
535

×
UNCOV
536
        // If a txid was not provided, then we should dispatch upon seeing the
×
UNCOV
537
        // script on-chain, so we'll short-circuit straight to scanning manually
×
UNCOV
538
        // as there doesn't exist a script index to query.
×
UNCOV
539
        if confRequest.TxID == chainntnfs.ZeroHash {
×
UNCOV
540
                return b.confDetailsManually(
×
UNCOV
541
                        confRequest, startHeight, endHeight,
×
UNCOV
542
                )
×
UNCOV
543
        }
×
544

545
        // Otherwise, we'll dispatch upon seeing a transaction on-chain with the
546
        // given hash.
547
        //
548
        // We'll first attempt to retrieve the transaction using the node's
549
        // txindex.
UNCOV
550
        txNotFoundErr := "No such mempool or blockchain transaction"
×
UNCOV
551
        txConf, txStatus, err := chainntnfs.ConfDetailsFromTxIndex(
×
UNCOV
552
                b.chainConn, confRequest, txNotFoundErr,
×
UNCOV
553
        )
×
UNCOV
554

×
UNCOV
555
        // We'll then check the status of the transaction lookup returned to
×
UNCOV
556
        // determine whether we should proceed with any fallback methods.
×
UNCOV
557
        switch {
×
558

559
        // We failed querying the index for the transaction, fall back to
560
        // scanning manually.
UNCOV
561
        case err != nil:
×
UNCOV
562
                chainntnfs.Log.Debugf("Failed getting conf details from "+
×
UNCOV
563
                        "index (%v), scanning manually", err)
×
UNCOV
564
                return b.confDetailsManually(confRequest, startHeight, endHeight)
×
565

566
        // The transaction was found within the node's mempool.
UNCOV
567
        case txStatus == chainntnfs.TxFoundMempool:
×
568

569
        // The transaction was found within the node's txindex.
UNCOV
570
        case txStatus == chainntnfs.TxFoundIndex:
×
571

572
        // The transaction was not found within the node's mempool or txindex.
UNCOV
573
        case txStatus == chainntnfs.TxNotFoundIndex:
×
574

575
        // Unexpected txStatus returned.
576
        default:
×
577
                return nil, txStatus,
×
578
                        fmt.Errorf("Got unexpected txConfStatus: %v", txStatus)
×
579
        }
580

UNCOV
581
        return txConf, txStatus, nil
×
582
}
583

584
// confDetailsManually looks up whether a transaction/output script has already
585
// been included in a block in the active chain by scanning the chain's blocks
586
// within the given range. If the transaction/output script is found, its
587
// confirmation details are returned. Otherwise, nil is returned.
588
func (b *BitcoindNotifier) confDetailsManually(confRequest chainntnfs.ConfRequest,
589
        heightHint, currentHeight uint32) (*chainntnfs.TxConfirmation,
UNCOV
590
        chainntnfs.TxConfStatus, error) {
×
UNCOV
591

×
UNCOV
592
        // Begin scanning blocks at every height to determine where the
×
UNCOV
593
        // transaction was included in.
×
UNCOV
594
        for height := currentHeight; height >= heightHint && height > 0; height-- {
×
UNCOV
595
                // Ensure we haven't been requested to shut down before
×
UNCOV
596
                // processing the next height.
×
UNCOV
597
                select {
×
598
                case <-b.quit:
×
599
                        return nil, chainntnfs.TxNotFoundManually,
×
600
                                chainntnfs.ErrChainNotifierShuttingDown
×
UNCOV
601
                default:
×
602
                }
603

UNCOV
604
                blockHash, err := b.chainConn.GetBlockHash(int64(height))
×
UNCOV
605
                if err != nil {
×
606
                        return nil, chainntnfs.TxNotFoundManually,
×
607
                                fmt.Errorf("unable to get hash from block "+
×
608
                                        "with height %d", height)
×
609
                }
×
610

UNCOV
611
                block, err := b.GetBlock(blockHash)
×
UNCOV
612
                if err != nil {
×
613
                        return nil, chainntnfs.TxNotFoundManually,
×
614
                                fmt.Errorf("unable to get block with hash "+
×
615
                                        "%v: %v", blockHash, err)
×
616
                }
×
617

618
                // For every transaction in the block, check which one matches
619
                // our request. If we find one that does, we can dispatch its
620
                // confirmation details.
UNCOV
621
                for txIndex, tx := range block.Transactions {
×
UNCOV
622
                        if !confRequest.MatchesTx(tx) {
×
UNCOV
623
                                continue
×
624
                        }
625

UNCOV
626
                        return &chainntnfs.TxConfirmation{
×
UNCOV
627
                                Tx:          tx.Copy(),
×
UNCOV
628
                                BlockHash:   blockHash,
×
UNCOV
629
                                BlockHeight: height,
×
UNCOV
630
                                TxIndex:     uint32(txIndex),
×
UNCOV
631
                                Block:       block,
×
UNCOV
632
                        }, chainntnfs.TxFoundManually, nil
×
633
                }
634
        }
635

636
        // If we reach here, then we were not able to find the transaction
637
        // within a block, so we avoid returning an error.
UNCOV
638
        return nil, chainntnfs.TxNotFoundManually, nil
×
639
}
640

641
// handleBlockConnected applies a chain update for a new block. Any watched
642
// transactions included this block will processed to either send notifications
643
// now or after numConfirmations confs.
UNCOV
644
func (b *BitcoindNotifier) handleBlockConnected(block chainntnfs.BlockEpoch) error {
×
UNCOV
645
        // First, we'll fetch the raw block as we'll need to gather all the
×
UNCOV
646
        // transactions to determine whether any are relevant to our registered
×
UNCOV
647
        // clients.
×
UNCOV
648
        rawBlock, err := b.GetBlock(block.Hash)
×
UNCOV
649
        if err != nil {
×
650
                return fmt.Errorf("unable to get block: %w", err)
×
651
        }
×
UNCOV
652
        utilBlock := btcutil.NewBlock(rawBlock)
×
UNCOV
653

×
UNCOV
654
        // We'll then extend the txNotifier's height with the information of
×
UNCOV
655
        // this new block, which will handle all of the notification logic for
×
UNCOV
656
        // us.
×
UNCOV
657
        err = b.txNotifier.ConnectTip(utilBlock, uint32(block.Height))
×
UNCOV
658
        if err != nil {
×
659
                return fmt.Errorf("unable to connect tip: %w", err)
×
660
        }
×
661

UNCOV
662
        chainntnfs.Log.Infof("New block: height=%v, sha=%v", block.Height,
×
UNCOV
663
                block.Hash)
×
UNCOV
664

×
UNCOV
665
        // Now that we've guaranteed the new block extends the txNotifier's
×
UNCOV
666
        // current tip, we'll proceed to dispatch notifications to all of our
×
UNCOV
667
        // registered clients whom have had notifications fulfilled. Before
×
UNCOV
668
        // doing so, we'll make sure update our in memory state in order to
×
UNCOV
669
        // satisfy any client requests based upon the new block.
×
UNCOV
670
        b.bestBlock = block
×
UNCOV
671

×
UNCOV
672
        err = b.txNotifier.NotifyHeight(uint32(block.Height))
×
UNCOV
673
        if err != nil {
×
674
                return fmt.Errorf("unable to notify height: %w", err)
×
675
        }
×
676

UNCOV
677
        b.notifyBlockEpochs(block.Height, block.Hash, block.BlockHeader)
×
UNCOV
678

×
UNCOV
679
        return nil
×
680
}
681

682
// notifyBlockEpochs notifies all registered block epoch clients of the newly
683
// connected block to the main chain.
684
func (b *BitcoindNotifier) notifyBlockEpochs(newHeight int32, newSha *chainhash.Hash,
UNCOV
685
        blockHeader *wire.BlockHeader) {
×
UNCOV
686

×
UNCOV
687
        for _, client := range b.blockEpochClients {
×
UNCOV
688
                b.notifyBlockEpochClient(client, newHeight, newSha, blockHeader)
×
UNCOV
689
        }
×
690
}
691

692
// notifyBlockEpochClient sends a registered block epoch client a notification
693
// about a specific block.
694
func (b *BitcoindNotifier) notifyBlockEpochClient(epochClient *blockEpochRegistration,
UNCOV
695
        height int32, sha *chainhash.Hash, header *wire.BlockHeader) {
×
UNCOV
696

×
UNCOV
697
        epoch := &chainntnfs.BlockEpoch{
×
UNCOV
698
                Height:      height,
×
UNCOV
699
                Hash:        sha,
×
UNCOV
700
                BlockHeader: header,
×
UNCOV
701
        }
×
UNCOV
702

×
UNCOV
703
        select {
×
UNCOV
704
        case epochClient.epochQueue.ChanIn() <- epoch:
×
705
        case <-epochClient.cancelChan:
×
706
        case <-b.quit:
×
707
        }
708
}
709

710
// RegisterSpendNtfn registers an intent to be notified once the target
711
// outpoint/output script has been spent by a transaction on-chain. When
712
// intending to be notified of the spend of an output script, a nil outpoint
713
// must be used. The heightHint should represent the earliest height in the
714
// chain of the transaction that spent the outpoint/output script.
715
//
716
// Once a spend of has been detected, the details of the spending event will be
717
// sent across the 'Spend' channel.
718
func (b *BitcoindNotifier) RegisterSpendNtfn(outpoint *wire.OutPoint,
UNCOV
719
        pkScript []byte, heightHint uint32) (*chainntnfs.SpendEvent, error) {
×
UNCOV
720

×
UNCOV
721
        // Register the conf notification with the TxNotifier. A non-nil value
×
UNCOV
722
        // for `dispatch` will be returned if we are required to perform a
×
UNCOV
723
        // manual scan for the confirmation. Otherwise the notifier will begin
×
UNCOV
724
        // watching at tip for the transaction to confirm.
×
UNCOV
725
        ntfn, err := b.txNotifier.RegisterSpend(outpoint, pkScript, heightHint)
×
UNCOV
726
        if err != nil {
×
UNCOV
727
                return nil, err
×
UNCOV
728
        }
×
729

730
        // We'll then request the backend to notify us when it has detected the
731
        // outpoint/output script as spent.
732
        //
733
        // TODO(wilmer): use LoadFilter API instead.
UNCOV
734
        if outpoint == nil || *outpoint == chainntnfs.ZeroOutPoint {
×
UNCOV
735
                _, addrs, _, err := txscript.ExtractPkScriptAddrs(
×
UNCOV
736
                        pkScript, b.chainParams,
×
UNCOV
737
                )
×
UNCOV
738
                if err != nil {
×
739
                        return nil, fmt.Errorf("unable to parse script: %w",
×
740
                                err)
×
741
                }
×
UNCOV
742
                if err := b.chainConn.NotifyReceived(addrs); err != nil {
×
743
                        return nil, err
×
744
                }
×
UNCOV
745
        } else {
×
UNCOV
746
                ops := []*wire.OutPoint{outpoint}
×
UNCOV
747
                if err := b.chainConn.NotifySpent(ops); err != nil {
×
748
                        return nil, err
×
749
                }
×
750
        }
751

752
        // If the txNotifier didn't return any details to perform a historical
753
        // scan of the chain, then we can return early as there's nothing left
754
        // for us to do.
UNCOV
755
        if ntfn.HistoricalDispatch == nil {
×
UNCOV
756
                return ntfn.Event, nil
×
UNCOV
757
        }
×
758

759
        // Otherwise, we'll need to dispatch a historical rescan to determine if
760
        // the outpoint was already spent at a previous height.
761
        //
762
        // We'll short-circuit the path when dispatching the spend of a script,
763
        // rather than an outpoint, as there aren't any additional checks we can
764
        // make for scripts.
UNCOV
765
        if ntfn.HistoricalDispatch.OutPoint == chainntnfs.ZeroOutPoint {
×
UNCOV
766
                select {
×
UNCOV
767
                case b.notificationRegistry <- ntfn.HistoricalDispatch:
×
768
                case <-b.quit:
×
769
                        return nil, chainntnfs.ErrChainNotifierShuttingDown
×
770
                }
771

UNCOV
772
                return ntfn.Event, nil
×
773
        }
774

775
        // When dispatching spends of outpoints, there are a number of checks we
776
        // can make to start our rescan from a better height or completely avoid
777
        // it.
778
        //
779
        // We'll start by checking the backend's UTXO set to determine whether
780
        // the outpoint has been spent. If it hasn't, we can return to the
781
        // caller as well.
UNCOV
782
        txOut, err := b.chainConn.GetTxOut(&outpoint.Hash, outpoint.Index, true)
×
UNCOV
783
        if err != nil {
×
784
                return nil, err
×
785
        }
×
UNCOV
786
        if txOut != nil {
×
UNCOV
787
                // We'll let the txNotifier know the outpoint is still unspent
×
UNCOV
788
                // in order to begin updating its spend hint.
×
UNCOV
789
                err := b.txNotifier.UpdateSpendDetails(
×
UNCOV
790
                        ntfn.HistoricalDispatch.SpendRequest, nil,
×
UNCOV
791
                )
×
UNCOV
792
                if err != nil {
×
793
                        return nil, err
×
794
                }
×
795

UNCOV
796
                return ntfn.Event, nil
×
797
        }
798

799
        // Since the outpoint was spent, as it no longer exists within the UTXO
800
        // set, we'll determine when it happened by scanning the chain.
801
        //
802
        // As a minimal optimization, we'll query the backend's transaction
803
        // index (if enabled) to determine if we have a better rescan starting
804
        // height. We can do this as the GetRawTransaction call will return the
805
        // hash of the block it was included in within the chain.
UNCOV
806
        tx, err := b.chainConn.GetRawTransactionVerbose(&outpoint.Hash)
×
UNCOV
807
        if err != nil {
×
UNCOV
808
                // Avoid returning an error if the transaction was not found to
×
UNCOV
809
                // proceed with fallback methods.
×
UNCOV
810
                jsonErr, ok := err.(*btcjson.RPCError)
×
UNCOV
811
                if !ok || jsonErr.Code != btcjson.ErrRPCNoTxInfo {
×
812
                        return nil, fmt.Errorf("unable to query for txid "+
×
813
                                "%v: %w", outpoint.Hash, err)
×
814
                }
×
815
        }
816

817
        // If the transaction index was enabled, we'll use the block's hash to
818
        // retrieve its height and check whether it provides a better starting
819
        // point for our rescan.
UNCOV
820
        if tx != nil {
×
UNCOV
821
                // If the transaction containing the outpoint hasn't confirmed
×
UNCOV
822
                // on-chain, then there's no need to perform a rescan.
×
UNCOV
823
                if tx.BlockHash == "" {
×
UNCOV
824
                        return ntfn.Event, nil
×
UNCOV
825
                }
×
826

UNCOV
827
                blockHash, err := chainhash.NewHashFromStr(tx.BlockHash)
×
UNCOV
828
                if err != nil {
×
829
                        return nil, err
×
830
                }
×
UNCOV
831
                blockHeight, err := b.chainConn.GetBlockHeight(blockHash)
×
UNCOV
832
                if err != nil {
×
833
                        return nil, err
×
834
                }
×
835

UNCOV
836
                if uint32(blockHeight) > ntfn.HistoricalDispatch.StartHeight {
×
UNCOV
837
                        ntfn.HistoricalDispatch.StartHeight = uint32(blockHeight)
×
UNCOV
838
                }
×
839
        }
840

841
        // Now that we've determined the starting point of our rescan, we can
842
        // dispatch it and return.
UNCOV
843
        select {
×
UNCOV
844
        case b.notificationRegistry <- ntfn.HistoricalDispatch:
×
845
        case <-b.quit:
×
846
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
847
        }
848

UNCOV
849
        return ntfn.Event, nil
×
850
}
851

852
// historicalSpendDetails attempts to manually scan the chain within the given
853
// height range for a transaction that spends the given outpoint/output script.
854
// If one is found, the spend details are assembled and returned to the caller.
855
// If the spend is not found, a nil spend detail will be returned.
856
func (b *BitcoindNotifier) historicalSpendDetails(
857
        spendRequest chainntnfs.SpendRequest, startHeight, endHeight uint32) (
UNCOV
858
        *chainntnfs.SpendDetail, error) {
×
UNCOV
859

×
UNCOV
860
        // Begin scanning blocks at every height to determine if the outpoint
×
UNCOV
861
        // was spent.
×
UNCOV
862
        for height := endHeight; height >= startHeight && height > 0; height-- {
×
UNCOV
863
                // Ensure we haven't been requested to shut down before
×
UNCOV
864
                // processing the next height.
×
UNCOV
865
                select {
×
866
                case <-b.quit:
×
867
                        return nil, chainntnfs.ErrChainNotifierShuttingDown
×
UNCOV
868
                default:
×
869
                }
870

871
                // First, we'll fetch the block for the current height.
UNCOV
872
                blockHash, err := b.chainConn.GetBlockHash(int64(height))
×
UNCOV
873
                if err != nil {
×
874
                        return nil, fmt.Errorf("unable to retrieve hash for "+
×
875
                                "block with height %d: %v", height, err)
×
876
                }
×
UNCOV
877
                block, err := b.GetBlock(blockHash)
×
UNCOV
878
                if err != nil {
×
879
                        return nil, fmt.Errorf("unable to retrieve block "+
×
880
                                "with hash %v: %v", blockHash, err)
×
881
                }
×
882

883
                // Then, we'll manually go over every input in every transaction
884
                // in it and determine whether it spends the request in
885
                // question. If we find one, we'll dispatch the spend details.
UNCOV
886
                for _, tx := range block.Transactions {
×
UNCOV
887
                        matches, inputIdx, err := spendRequest.MatchesTx(tx)
×
UNCOV
888
                        if err != nil {
×
889
                                return nil, err
×
890
                        }
×
UNCOV
891
                        if !matches {
×
UNCOV
892
                                continue
×
893
                        }
894

UNCOV
895
                        txCopy := tx.Copy()
×
UNCOV
896
                        txHash := txCopy.TxHash()
×
UNCOV
897
                        spendOutPoint := &txCopy.TxIn[inputIdx].PreviousOutPoint
×
UNCOV
898
                        return &chainntnfs.SpendDetail{
×
UNCOV
899
                                SpentOutPoint:     spendOutPoint,
×
UNCOV
900
                                SpenderTxHash:     &txHash,
×
UNCOV
901
                                SpendingTx:        txCopy,
×
UNCOV
902
                                SpenderInputIndex: inputIdx,
×
UNCOV
903
                                SpendingHeight:    int32(height),
×
UNCOV
904
                        }, nil
×
905
                }
906
        }
907

UNCOV
908
        return nil, nil
×
909
}
910

911
// RegisterConfirmationsNtfn registers an intent to be notified once the target
912
// txid/output script has reached numConfs confirmations on-chain. When
913
// intending to be notified of the confirmation of an output script, a nil txid
914
// must be used. The heightHint should represent the earliest height at which
915
// the txid/output script could have been included in the chain.
916
//
917
// Progress on the number of confirmations left can be read from the 'Updates'
918
// channel. Once it has reached all of its confirmations, a notification will be
919
// sent across the 'Confirmed' channel.
920
func (b *BitcoindNotifier) RegisterConfirmationsNtfn(txid *chainhash.Hash,
921
        pkScript []byte, numConfs, heightHint uint32,
UNCOV
922
        opts ...chainntnfs.NotifierOption) (*chainntnfs.ConfirmationEvent, error) {
×
UNCOV
923

×
UNCOV
924
        // Register the conf notification with the TxNotifier. A non-nil value
×
UNCOV
925
        // for `dispatch` will be returned if we are required to perform a
×
UNCOV
926
        // manual scan for the confirmation. Otherwise the notifier will begin
×
UNCOV
927
        // watching at tip for the transaction to confirm.
×
UNCOV
928
        ntfn, err := b.txNotifier.RegisterConf(
×
UNCOV
929
                txid, pkScript, numConfs, heightHint, opts...,
×
UNCOV
930
        )
×
UNCOV
931
        if err != nil {
×
932
                return nil, err
×
933
        }
×
934

UNCOV
935
        if ntfn.HistoricalDispatch == nil {
×
UNCOV
936
                return ntfn.Event, nil
×
UNCOV
937
        }
×
938

UNCOV
939
        select {
×
UNCOV
940
        case b.notificationRegistry <- ntfn.HistoricalDispatch:
×
UNCOV
941
                return ntfn.Event, nil
×
942
        case <-b.quit:
×
943
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
944
        }
945
}
946

947
// blockEpochRegistration represents a client's intent to receive a
948
// notification with each newly connected block.
949
type blockEpochRegistration struct {
950
        epochID uint64
951

952
        epochChan chan *chainntnfs.BlockEpoch
953

954
        epochQueue *queue.ConcurrentQueue
955

956
        bestBlock *chainntnfs.BlockEpoch
957

958
        errorChan chan error
959

960
        cancelChan chan struct{}
961

962
        wg sync.WaitGroup
963
}
964

965
// epochCancel is a message sent to the BitcoindNotifier when a client wishes
966
// to cancel an outstanding epoch notification that has yet to be dispatched.
967
type epochCancel struct {
968
        epochID uint64
969
}
970

971
// RegisterBlockEpochNtfn returns a BlockEpochEvent which subscribes the
972
// caller to receive notifications, of each new block connected to the main
973
// chain. Clients have the option of passing in their best known block, which
974
// the notifier uses to check if they are behind on blocks and catch them up. If
975
// they do not provide one, then a notification will be dispatched immediately
976
// for the current tip of the chain upon a successful registration.
977
func (b *BitcoindNotifier) RegisterBlockEpochNtfn(
UNCOV
978
        bestBlock *chainntnfs.BlockEpoch) (*chainntnfs.BlockEpochEvent, error) {
×
UNCOV
979

×
UNCOV
980
        reg := &blockEpochRegistration{
×
UNCOV
981
                epochQueue: queue.NewConcurrentQueue(20),
×
UNCOV
982
                epochChan:  make(chan *chainntnfs.BlockEpoch, 20),
×
UNCOV
983
                cancelChan: make(chan struct{}),
×
UNCOV
984
                epochID:    atomic.AddUint64(&b.epochClientCounter, 1),
×
UNCOV
985
                bestBlock:  bestBlock,
×
UNCOV
986
                errorChan:  make(chan error, 1),
×
UNCOV
987
        }
×
UNCOV
988
        reg.epochQueue.Start()
×
UNCOV
989

×
UNCOV
990
        // Before we send the request to the main goroutine, we'll launch a new
×
UNCOV
991
        // goroutine to proxy items added to our queue to the client itself.
×
UNCOV
992
        // This ensures that all notifications are received *in order*.
×
UNCOV
993
        reg.wg.Add(1)
×
UNCOV
994
        go func() {
×
UNCOV
995
                defer reg.wg.Done()
×
UNCOV
996

×
UNCOV
997
                for {
×
UNCOV
998
                        select {
×
UNCOV
999
                        case ntfn := <-reg.epochQueue.ChanOut():
×
UNCOV
1000
                                blockNtfn := ntfn.(*chainntnfs.BlockEpoch)
×
UNCOV
1001
                                select {
×
UNCOV
1002
                                case reg.epochChan <- blockNtfn:
×
1003

UNCOV
1004
                                case <-reg.cancelChan:
×
UNCOV
1005
                                        return
×
1006

UNCOV
1007
                                case <-b.quit:
×
UNCOV
1008
                                        return
×
1009
                                }
1010

UNCOV
1011
                        case <-reg.cancelChan:
×
UNCOV
1012
                                return
×
1013

UNCOV
1014
                        case <-b.quit:
×
UNCOV
1015
                                return
×
1016
                        }
1017
                }
1018
        }()
1019

UNCOV
1020
        select {
×
1021
        case <-b.quit:
×
1022
                // As we're exiting before the registration could be sent,
×
1023
                // we'll stop the queue now ourselves.
×
1024
                reg.epochQueue.Stop()
×
1025

×
1026
                return nil, errors.New("chainntnfs: system interrupt while " +
×
1027
                        "attempting to register for block epoch notification.")
×
UNCOV
1028
        case b.notificationRegistry <- reg:
×
UNCOV
1029
                return &chainntnfs.BlockEpochEvent{
×
UNCOV
1030
                        Epochs: reg.epochChan,
×
UNCOV
1031
                        Cancel: func() {
×
UNCOV
1032
                                cancel := &epochCancel{
×
UNCOV
1033
                                        epochID: reg.epochID,
×
UNCOV
1034
                                }
×
UNCOV
1035

×
UNCOV
1036
                                // Submit epoch cancellation to notification dispatcher.
×
UNCOV
1037
                                select {
×
UNCOV
1038
                                case b.notificationCancels <- cancel:
×
UNCOV
1039
                                        // Cancellation is being handled, drain the epoch channel until it is
×
UNCOV
1040
                                        // closed before yielding to caller.
×
UNCOV
1041
                                        for {
×
UNCOV
1042
                                                select {
×
UNCOV
1043
                                                case _, ok := <-reg.epochChan:
×
UNCOV
1044
                                                        if !ok {
×
UNCOV
1045
                                                                return
×
UNCOV
1046
                                                        }
×
1047
                                                case <-b.quit:
×
1048
                                                        return
×
1049
                                                }
1050
                                        }
UNCOV
1051
                                case <-b.quit:
×
1052
                                }
1053
                        },
1054
                }, nil
1055
        }
1056
}
1057

1058
// GetBlock is used to retrieve the block with the given hash. This function
1059
// wraps the blockCache's GetBlock function.
1060
func (b *BitcoindNotifier) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock,
UNCOV
1061
        error) {
×
UNCOV
1062

×
UNCOV
1063
        return b.blockCache.GetBlock(hash, b.chainConn.GetBlock)
×
UNCOV
1064
}
×
1065

1066
// SubscribeMempoolSpent allows the caller to register a subscription to watch
1067
// for a spend of an outpoint in the mempool.The event will be dispatched once
1068
// the outpoint is spent in the mempool.
1069
//
1070
// NOTE: part of the MempoolWatcher interface.
1071
func (b *BitcoindNotifier) SubscribeMempoolSpent(
UNCOV
1072
        outpoint wire.OutPoint) (*chainntnfs.MempoolSpendEvent, error) {
×
UNCOV
1073

×
UNCOV
1074
        event := b.memNotifier.SubscribeInput(outpoint)
×
UNCOV
1075

×
UNCOV
1076
        ops := []*wire.OutPoint{&outpoint}
×
UNCOV
1077

×
UNCOV
1078
        return event, b.chainConn.NotifySpent(ops)
×
UNCOV
1079
}
×
1080

1081
// CancelMempoolSpendEvent allows the caller to cancel a subscription to watch
1082
// for a spend of an outpoint in the mempool.
1083
//
1084
// NOTE: part of the MempoolWatcher interface.
1085
func (b *BitcoindNotifier) CancelMempoolSpendEvent(
UNCOV
1086
        sub *chainntnfs.MempoolSpendEvent) {
×
UNCOV
1087

×
UNCOV
1088
        b.memNotifier.UnsubscribeEvent(sub)
×
UNCOV
1089
}
×
1090

1091
// LookupInputMempoolSpend takes an outpoint and queries the mempool to find
1092
// its spending tx. Returns the tx if found, otherwise fn.None.
1093
//
1094
// NOTE: part of the MempoolWatcher interface.
1095
func (b *BitcoindNotifier) LookupInputMempoolSpend(
UNCOV
1096
        op wire.OutPoint) fn.Option[wire.MsgTx] {
×
UNCOV
1097

×
UNCOV
1098
        // Find the spending txid.
×
UNCOV
1099
        txid, found := b.chainConn.LookupInputMempoolSpend(op)
×
UNCOV
1100
        if !found {
×
UNCOV
1101
                return fn.None[wire.MsgTx]()
×
UNCOV
1102
        }
×
1103

1104
        // Query the spending tx using the id.
UNCOV
1105
        tx, err := b.chainConn.GetRawTransaction(&txid)
×
UNCOV
1106
        if err != nil {
×
1107
                // TODO(yy): enable logging errors in this package.
×
1108
                return fn.None[wire.MsgTx]()
×
1109
        }
×
1110

UNCOV
1111
        return fn.Some(*tx.MsgTx().Copy())
×
1112
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc