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

lightningnetwork / lnd / 15782265189

20 Jun 2025 03:23PM UTC coverage: 68.14% (-0.003%) from 68.143%
15782265189

Pull #9958

github

web-flow
Merge ae1a1d1ba into 7857d2c6a
Pull Request #9958: improve CloseChannel docs

134478 of 197355 relevant lines covered (68.14%)

22170.18 hits per line

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

82.09
/chainntnfs/btcdnotify/btcd.go
1
package btcdnotify
2

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

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

24
const (
25
        // notifierType uniquely identifies this concrete implementation of the
26
        // ChainNotifier interface.
27
        notifierType = "btcd"
28
)
29

30
// chainUpdate encapsulates an update to the current main chain. This struct is
31
// used as an element within an unbounded queue in order to avoid blocking the
32
// main rpc dispatch rule.
33
type chainUpdate struct {
34
        blockHash   *chainhash.Hash
35
        blockHeight int32
36

37
        // connected is true if this update is a new block and false if it is a
38
        // disconnected block.
39
        connect bool
40
}
41

42
// txUpdate encapsulates a transaction related notification sent from btcd to
43
// the registered RPC client. This struct is used as an element within an
44
// unbounded queue in order to avoid blocking the main rpc dispatch rule.
45
type txUpdate struct {
46
        tx      *btcutil.Tx
47
        details *btcjson.BlockDetails
48
}
49

50
// TODO(roasbeef): generalize struct below:
51
//  * move chans to config, allow outside callers to handle send conditions
52

53
// BtcdNotifier implements the ChainNotifier interface using btcd's websockets
54
// notifications. Multiple concurrent clients are supported. All notifications
55
// are achieved via non-blocking sends on client channels.
56
type BtcdNotifier struct {
57
        epochClientCounter uint64 // To be used atomically.
58

59
        start   sync.Once
60
        active  int32 // To be used atomically.
61
        stopped int32 // To be used atomically.
62

63
        chainConn   *chain.RPCClient
64
        chainParams *chaincfg.Params
65

66
        notificationCancels  chan interface{}
67
        notificationRegistry chan interface{}
68

69
        txNotifier *chainntnfs.TxNotifier
70

71
        blockEpochClients map[uint64]*blockEpochRegistration
72

73
        bestBlock chainntnfs.BlockEpoch
74

75
        // blockCache is a LRU block cache.
76
        blockCache *blockcache.BlockCache
77

78
        chainUpdates *queue.ConcurrentQueue
79
        txUpdates    *queue.ConcurrentQueue
80

81
        // spendHintCache is a cache used to query and update the latest height
82
        // hints for an outpoint. Each height hint represents the earliest
83
        // height at which the outpoint could have been spent within the chain.
84
        spendHintCache chainntnfs.SpendHintCache
85

86
        // confirmHintCache is a cache used to query the latest height hints for
87
        // a transaction. Each height hint represents the earliest height at
88
        // which the transaction could have confirmed within the chain.
89
        confirmHintCache chainntnfs.ConfirmHintCache
90

91
        // memNotifier notifies clients of events related to the mempool.
92
        memNotifier *chainntnfs.MempoolNotifier
93

94
        wg   sync.WaitGroup
95
        quit chan struct{}
96
}
97

98
// Ensure BtcdNotifier implements the ChainNotifier interface at compile time.
99
var _ chainntnfs.ChainNotifier = (*BtcdNotifier)(nil)
100

101
// Ensure BtcdNotifier implements the MempoolWatcher interface at compile time.
102
var _ chainntnfs.MempoolWatcher = (*BtcdNotifier)(nil)
103

104
// New returns a new BtcdNotifier instance. This function assumes the btcd node
105
// detailed in the passed configuration is already running, and willing to
106
// accept new websockets clients.
107
func New(config *rpcclient.ConnConfig, chainParams *chaincfg.Params,
108
        spendHintCache chainntnfs.SpendHintCache,
109
        confirmHintCache chainntnfs.ConfirmHintCache,
110
        blockCache *blockcache.BlockCache) (*BtcdNotifier, error) {
11✔
111

11✔
112
        notifier := &BtcdNotifier{
11✔
113
                chainParams: chainParams,
11✔
114

11✔
115
                notificationCancels:  make(chan interface{}),
11✔
116
                notificationRegistry: make(chan interface{}),
11✔
117

11✔
118
                blockEpochClients: make(map[uint64]*blockEpochRegistration),
11✔
119

11✔
120
                chainUpdates: queue.NewConcurrentQueue(10),
11✔
121
                txUpdates:    queue.NewConcurrentQueue(10),
11✔
122

11✔
123
                spendHintCache:   spendHintCache,
11✔
124
                confirmHintCache: confirmHintCache,
11✔
125

11✔
126
                blockCache:  blockCache,
11✔
127
                memNotifier: chainntnfs.NewMempoolNotifier(),
11✔
128

11✔
129
                quit: make(chan struct{}),
11✔
130
        }
11✔
131

11✔
132
        ntfnCallbacks := &rpcclient.NotificationHandlers{
11✔
133
                OnBlockConnected:    notifier.onBlockConnected,
11✔
134
                OnBlockDisconnected: notifier.onBlockDisconnected,
11✔
135
                OnRedeemingTx:       notifier.onRedeemingTx,
11✔
136
        }
11✔
137

11✔
138
        rpcCfg := &chain.RPCClientConfig{
11✔
139
                ReconnectAttempts:    20,
11✔
140
                Conn:                 config,
11✔
141
                Chain:                chainParams,
11✔
142
                NotificationHandlers: ntfnCallbacks,
11✔
143
        }
11✔
144

11✔
145
        chainRPC, err := chain.NewRPCClientWithConfig(rpcCfg)
11✔
146
        if err != nil {
11✔
147
                return nil, err
×
148
        }
×
149

150
        notifier.chainConn = chainRPC
11✔
151

11✔
152
        return notifier, nil
11✔
153
}
154

155
// Start connects to the running btcd node over websockets, registers for block
156
// notifications, and finally launches all related helper goroutines.
157
func (b *BtcdNotifier) Start() error {
8✔
158
        var startErr error
8✔
159
        b.start.Do(func() {
16✔
160
                startErr = b.startNotifier()
8✔
161
        })
8✔
162

163
        return startErr
8✔
164
}
165

166
// Started returns true if this instance has been started, and false otherwise.
167
func (b *BtcdNotifier) Started() bool {
1✔
168
        return atomic.LoadInt32(&b.active) != 0
1✔
169
}
1✔
170

171
// Stop shutsdown the BtcdNotifier.
172
func (b *BtcdNotifier) Stop() error {
7✔
173
        // Already shutting down?
7✔
174
        if atomic.AddInt32(&b.stopped, 1) != 1 {
7✔
175
                return nil
×
176
        }
×
177

178
        chainntnfs.Log.Info("btcd notifier shutting down...")
7✔
179
        defer chainntnfs.Log.Debug("btcd notifier shutdown complete")
7✔
180

7✔
181
        // Shutdown the rpc client, this gracefully disconnects from btcd, and
7✔
182
        // cleans up all related resources.
7✔
183
        b.chainConn.Stop()
7✔
184

7✔
185
        close(b.quit)
7✔
186
        b.wg.Wait()
7✔
187

7✔
188
        b.chainUpdates.Stop()
7✔
189
        b.txUpdates.Stop()
7✔
190

7✔
191
        // Notify all pending clients of our shutdown by closing the related
7✔
192
        // notification channels.
7✔
193
        for _, epochClient := range b.blockEpochClients {
31✔
194
                close(epochClient.cancelChan)
24✔
195
                epochClient.wg.Wait()
24✔
196

24✔
197
                close(epochClient.epochChan)
24✔
198
        }
24✔
199
        b.txNotifier.TearDown()
7✔
200

7✔
201
        // Stop the mempool notifier.
7✔
202
        b.memNotifier.TearDown()
7✔
203

7✔
204
        return nil
7✔
205
}
206

207
// startNotifier is the main starting point for the BtcdNotifier. It connects
208
// to btcd and start the main dispatcher goroutine.
209
func (b *BtcdNotifier) startNotifier() error {
8✔
210
        chainntnfs.Log.Infof("btcd notifier starting...")
8✔
211

8✔
212
        // Start our concurrent queues before starting the chain connection, to
8✔
213
        // ensure onBlockConnected and onRedeemingTx callbacks won't be
8✔
214
        // blocked.
8✔
215
        b.chainUpdates.Start()
8✔
216
        b.txUpdates.Start()
8✔
217

8✔
218
        // Connect to btcd, and register for notifications on connected, and
8✔
219
        // disconnected blocks.
8✔
220
        if err := b.chainConn.Connect(20); err != nil {
8✔
221
                b.txUpdates.Stop()
×
222
                b.chainUpdates.Stop()
×
223
                return err
×
224
        }
×
225

226
        // Before we fetch the best block/block height we need to register the
227
        // notifications for connected blocks, otherwise we might think we are
228
        // at an earlier block height because during block notification
229
        // registration we might have already mined some new blocks. Hence we
230
        // will not get notified accordingly.
231
        if err := b.chainConn.NotifyBlocks(); err != nil {
8✔
232
                b.txUpdates.Stop()
×
233
                b.chainUpdates.Stop()
×
234
                return err
×
235
        }
×
236

237
        currentHash, currentHeight, err := b.chainConn.GetBestBlock()
8✔
238
        if err != nil {
8✔
239
                b.txUpdates.Stop()
×
240
                b.chainUpdates.Stop()
×
241
                return err
×
242
        }
×
243

244
        bestBlock, err := b.chainConn.GetBlock(currentHash)
8✔
245
        if err != nil {
8✔
246
                b.txUpdates.Stop()
×
247
                b.chainUpdates.Stop()
×
248
                return err
×
249
        }
×
250

251
        b.txNotifier = chainntnfs.NewTxNotifier(
8✔
252
                uint32(currentHeight), chainntnfs.ReorgSafetyLimit,
8✔
253
                b.confirmHintCache, b.spendHintCache,
8✔
254
        )
8✔
255

8✔
256
        b.bestBlock = chainntnfs.BlockEpoch{
8✔
257
                Height:      currentHeight,
8✔
258
                Hash:        currentHash,
8✔
259
                BlockHeader: &bestBlock.Header,
8✔
260
        }
8✔
261

8✔
262
        b.wg.Add(1)
8✔
263
        go b.notificationDispatcher()
8✔
264

8✔
265
        // Set the active flag now that we've completed the full
8✔
266
        // startup.
8✔
267
        atomic.StoreInt32(&b.active, 1)
8✔
268

8✔
269
        chainntnfs.Log.Debugf("btcd notifier started")
8✔
270

8✔
271
        return nil
8✔
272
}
273

274
// onBlockConnected implements on OnBlockConnected callback for rpcclient.
275
// Ingesting a block updates the wallet's internal utxo state based on the
276
// outputs created and destroyed within each block.
277
func (b *BtcdNotifier) onBlockConnected(hash *chainhash.Hash, height int32, t time.Time) {
897✔
278
        // Append this new chain update to the end of the queue of new chain
897✔
279
        // updates.
897✔
280
        select {
897✔
281
        case b.chainUpdates.ChanIn() <- &chainUpdate{
282
                blockHash:   hash,
283
                blockHeight: height,
284
                connect:     true,
285
        }:
897✔
286
        case <-b.quit:
×
287
                return
×
288
        }
289
}
290

291
// filteredBlock represents a new block which has been connected to the main
292
// chain. The slice of transactions will only be populated if the block
293
// includes a transaction that confirmed one of our watched txids, or spends
294
// one of the outputs currently being watched.
295
//
296
// TODO(halseth): this is currently used for complete blocks. Change to use
297
// onFilteredBlockConnected and onFilteredBlockDisconnected, making it easier
298
// to unify with the Neutrino implementation.
299
type filteredBlock struct {
300
        hash   chainhash.Hash
301
        height uint32
302
        block  *btcutil.Block
303

304
        // connected is true if this update is a new block and false if it is a
305
        // disconnected block.
306
        connect bool
307
}
308

309
// onBlockDisconnected implements on OnBlockDisconnected callback for rpcclient.
310
func (b *BtcdNotifier) onBlockDisconnected(hash *chainhash.Hash, height int32, t time.Time) {
45✔
311
        // Append this new chain update to the end of the queue of new chain
45✔
312
        // updates.
45✔
313
        select {
45✔
314
        case b.chainUpdates.ChanIn() <- &chainUpdate{
315
                blockHash:   hash,
316
                blockHeight: height,
317
                connect:     false,
318
        }:
45✔
319
        case <-b.quit:
×
320
                return
×
321
        }
322
}
323

324
// onRedeemingTx implements on OnRedeemingTx callback for rpcclient.
325
func (b *BtcdNotifier) onRedeemingTx(tx *btcutil.Tx, details *btcjson.BlockDetails) {
10✔
326
        // Append this new transaction update to the end of the queue of new
10✔
327
        // chain updates.
10✔
328
        select {
10✔
329
        case b.txUpdates.ChanIn() <- &txUpdate{tx, details}:
10✔
330
        case <-b.quit:
×
331
                return
×
332
        }
333
}
334

335
// notificationDispatcher is the primary goroutine which handles client
336
// notification registrations, as well as notification dispatches.
337
func (b *BtcdNotifier) notificationDispatcher() {
11✔
338
        defer b.wg.Done()
11✔
339

11✔
340
out:
11✔
341
        for {
1,010✔
342
                select {
999✔
343
                case cancelMsg := <-b.notificationCancels:
2✔
344
                        switch msg := cancelMsg.(type) {
2✔
345
                        case *epochCancel:
2✔
346
                                chainntnfs.Log.Infof("Cancelling epoch "+
2✔
347
                                        "notification, epoch_id=%v", msg.epochID)
2✔
348

2✔
349
                                // First, we'll lookup the original
2✔
350
                                // registration in order to stop the active
2✔
351
                                // queue goroutine.
2✔
352
                                reg := b.blockEpochClients[msg.epochID]
2✔
353
                                reg.epochQueue.Stop()
2✔
354

2✔
355
                                // Next, close the cancel channel for this
2✔
356
                                // specific client, and wait for the client to
2✔
357
                                // exit.
2✔
358
                                close(b.blockEpochClients[msg.epochID].cancelChan)
2✔
359
                                b.blockEpochClients[msg.epochID].wg.Wait()
2✔
360

2✔
361
                                // Once the client has exited, we can then
2✔
362
                                // safely close the channel used to send epoch
2✔
363
                                // notifications, in order to notify any
2✔
364
                                // listeners that the intent has been
2✔
365
                                // canceled.
2✔
366
                                close(b.blockEpochClients[msg.epochID].epochChan)
2✔
367
                                delete(b.blockEpochClients, msg.epochID)
2✔
368
                        }
369
                case registerMsg := <-b.notificationRegistry:
59✔
370
                        switch msg := registerMsg.(type) {
59✔
371
                        case *chainntnfs.HistoricalConfDispatch:
35✔
372
                                // Look up whether the transaction/output script
35✔
373
                                // has already confirmed in the active chain.
35✔
374
                                // We'll do this in a goroutine to prevent
35✔
375
                                // blocking potentially long rescans.
35✔
376
                                //
35✔
377
                                // TODO(wilmer): add retry logic if rescan fails?
35✔
378
                                b.wg.Add(1)
35✔
379

35✔
380
                                //nolint:ll
35✔
381
                                go func(msg *chainntnfs.HistoricalConfDispatch) {
70✔
382
                                        defer b.wg.Done()
35✔
383

35✔
384
                                        confDetails, _, err := b.historicalConfDetails(
35✔
385
                                                msg.ConfRequest,
35✔
386
                                                msg.StartHeight, msg.EndHeight,
35✔
387
                                        )
35✔
388
                                        if err != nil {
35✔
389
                                                chainntnfs.Log.Error(err)
×
390
                                                return
×
391
                                        }
×
392

393
                                        // If the historical dispatch finished
394
                                        // without error, we will invoke
395
                                        // UpdateConfDetails even if none were
396
                                        // found. This allows the notifier to
397
                                        // begin safely updating the height hint
398
                                        // cache at tip, since any pending
399
                                        // rescans have now completed.
400
                                        err = b.txNotifier.UpdateConfDetails(
35✔
401
                                                msg.ConfRequest, confDetails,
35✔
402
                                        )
35✔
403
                                        if err != nil {
35✔
404
                                                chainntnfs.Log.Error(err)
×
405
                                        }
×
406
                                }(msg)
407

408
                        case *blockEpochRegistration:
25✔
409
                                chainntnfs.Log.Infof("New block epoch subscription")
25✔
410

25✔
411
                                b.blockEpochClients[msg.epochID] = msg
25✔
412

25✔
413
                                // If the client did not provide their best
25✔
414
                                // known block, then we'll immediately dispatch
25✔
415
                                // a notification for the current tip.
25✔
416
                                if msg.bestBlock == nil {
45✔
417
                                        b.notifyBlockEpochClient(
20✔
418
                                                msg, b.bestBlock.Height,
20✔
419
                                                b.bestBlock.Hash,
20✔
420
                                                b.bestBlock.BlockHeader,
20✔
421
                                        )
20✔
422

20✔
423
                                        msg.errorChan <- nil
20✔
424
                                        continue
20✔
425
                                }
426

427
                                // Otherwise, we'll attempt to deliver the
428
                                // backlog of notifications from their best
429
                                // known block.
430
                                missedBlocks, err := chainntnfs.GetClientMissedBlocks(
6✔
431
                                        b.chainConn, msg.bestBlock,
6✔
432
                                        b.bestBlock.Height, true,
6✔
433
                                )
6✔
434
                                if err != nil {
6✔
435
                                        msg.errorChan <- err
×
436
                                        continue
×
437
                                }
438

439
                                for _, block := range missedBlocks {
56✔
440
                                        b.notifyBlockEpochClient(
50✔
441
                                                msg, block.Height, block.Hash,
50✔
442
                                                block.BlockHeader,
50✔
443
                                        )
50✔
444
                                }
50✔
445

446
                                msg.errorChan <- nil
6✔
447
                        }
448

449
                case item := <-b.chainUpdates.ChanOut():
921✔
450
                        update := item.(*chainUpdate)
921✔
451
                        if update.connect {
1,798✔
452
                                blockHeader, err := b.chainConn.GetBlockHeader(
877✔
453
                                        update.blockHash,
877✔
454
                                )
877✔
455
                                if err != nil {
878✔
456
                                        chainntnfs.Log.Errorf("Unable to fetch "+
1✔
457
                                                "block header: %v", err)
1✔
458
                                        continue
1✔
459
                                }
460

461
                                if blockHeader.PrevBlock != *b.bestBlock.Hash {
878✔
462
                                        // Handle the case where the notifier
2✔
463
                                        // missed some blocks from its chain
2✔
464
                                        // backend
2✔
465
                                        chainntnfs.Log.Infof("Missed blocks, " +
2✔
466
                                                "attempting to catch up")
2✔
467
                                        newBestBlock, missedBlocks, err :=
2✔
468
                                                chainntnfs.HandleMissedBlocks(
2✔
469
                                                        b.chainConn,
2✔
470
                                                        b.txNotifier,
2✔
471
                                                        b.bestBlock,
2✔
472
                                                        update.blockHeight,
2✔
473
                                                        true,
2✔
474
                                                )
2✔
475
                                        if err != nil {
2✔
476
                                                // Set the bestBlock here in case
×
477
                                                // a catch up partially completed.
×
478
                                                b.bestBlock = newBestBlock
×
479
                                                chainntnfs.Log.Error(err)
×
480
                                                continue
×
481
                                        }
482

483
                                        for _, block := range missedBlocks {
23✔
484
                                                err := b.handleBlockConnected(block)
21✔
485
                                                if err != nil {
21✔
486
                                                        chainntnfs.Log.Error(err)
×
487
                                                        continue out
×
488
                                                }
489
                                        }
490
                                }
491

492
                                newBlock := chainntnfs.BlockEpoch{
876✔
493
                                        Height:      update.blockHeight,
876✔
494
                                        Hash:        update.blockHash,
876✔
495
                                        BlockHeader: blockHeader,
876✔
496
                                }
876✔
497
                                if err := b.handleBlockConnected(newBlock); err != nil {
876✔
498
                                        chainntnfs.Log.Error(err)
×
499
                                }
×
500
                                continue
876✔
501
                        }
502

503
                        if update.blockHeight != b.bestBlock.Height {
46✔
504
                                chainntnfs.Log.Infof("Missed disconnected" +
1✔
505
                                        "blocks, attempting to catch up")
1✔
506
                        }
1✔
507

508
                        newBestBlock, err := chainntnfs.RewindChain(
45✔
509
                                b.chainConn, b.txNotifier, b.bestBlock,
45✔
510
                                update.blockHeight-1,
45✔
511
                        )
45✔
512
                        if err != nil {
46✔
513
                                chainntnfs.Log.Errorf("Unable to rewind chain "+
1✔
514
                                        "from height %d to height %d: %v",
1✔
515
                                        b.bestBlock.Height, update.blockHeight-1, err)
1✔
516
                        }
1✔
517

518
                        // Set the bestBlock here in case a chain rewind
519
                        // partially completed.
520
                        b.bestBlock = newBestBlock
45✔
521

522
                case item := <-b.txUpdates.ChanOut():
10✔
523
                        newSpend := item.(*txUpdate)
10✔
524
                        tx := newSpend.tx
10✔
525

10✔
526
                        // Init values.
10✔
527
                        isMempool := false
10✔
528
                        height := uint32(0)
10✔
529

10✔
530
                        // Unwrap values.
10✔
531
                        if newSpend.details == nil {
15✔
532
                                isMempool = true
5✔
533
                        } else {
11✔
534
                                height = uint32(newSpend.details.Height)
6✔
535
                        }
6✔
536

537
                        // Handle the transaction.
538
                        b.handleRelevantTx(tx, isMempool, height)
10✔
539

540
                case <-b.quit:
7✔
541
                        break out
7✔
542
                }
543
        }
544
}
545

546
// handleRelevantTx handles a new transaction that has been seen either in a
547
// block or in the mempool. If in mempool, it will ask the mempool notifier to
548
// handle it. If in a block, it will ask the txNotifier to handle it, and
549
// cancel any relevant subscriptions made in the mempool.
550
func (b *BtcdNotifier) handleRelevantTx(tx *btcutil.Tx,
551
        mempool bool, height uint32) {
10✔
552

10✔
553
        // If this is a mempool spend, we'll ask the mempool notifier to handle
10✔
554
        // it.
10✔
555
        if mempool {
15✔
556
                err := b.memNotifier.ProcessRelevantSpendTx(tx)
5✔
557
                if err != nil {
5✔
558
                        chainntnfs.Log.Errorf("Unable to process transaction "+
×
559
                                "%v: %v", tx.Hash(), err)
×
560
                }
×
561

562
                return
5✔
563
        }
564

565
        // Otherwise this is a confirmed spend, and we'll ask the tx notifier
566
        // to handle it.
567
        err := b.txNotifier.ProcessRelevantSpendTx(tx, height)
6✔
568
        if err != nil {
6✔
569
                chainntnfs.Log.Errorf("Unable to process transaction %v: %v",
×
570
                        tx.Hash(), err)
×
571

×
572
                return
×
573
        }
×
574

575
        // Once the tx is processed, we will ask the memNotifier to unsubscribe
576
        // the input.
577
        //
578
        // NOTE(yy): we could build it into txNotifier.ProcessRelevantSpendTx,
579
        // but choose to implement it here so we can easily decouple the two
580
        // notifiers in the future.
581
        b.memNotifier.UnsubsribeConfirmedSpentTx(tx)
6✔
582
}
583

584
// historicalConfDetails looks up whether a confirmation request (txid/output
585
// script) has already been included in a block in the active chain and, if so,
586
// returns details about said block.
587
func (b *BtcdNotifier) historicalConfDetails(confRequest chainntnfs.ConfRequest,
588
        startHeight, endHeight uint32) (*chainntnfs.TxConfirmation,
589
        chainntnfs.TxConfStatus, error) {
41✔
590

41✔
591
        // If a txid was not provided, then we should dispatch upon seeing the
41✔
592
        // script on-chain, so we'll short-circuit straight to scanning manually
41✔
593
        // as there doesn't exist a script index to query.
41✔
594
        if confRequest.TxID == chainntnfs.ZeroHash {
57✔
595
                return b.confDetailsManually(
16✔
596
                        confRequest, startHeight, endHeight,
16✔
597
                )
16✔
598
        }
16✔
599

600
        // Otherwise, we'll dispatch upon seeing a transaction on-chain with the
601
        // given hash.
602
        //
603
        // We'll first attempt to retrieve the transaction using the node's
604
        // txindex.
605
        txNotFoundErr := "No information available about transaction"
25✔
606
        txConf, txStatus, err := chainntnfs.ConfDetailsFromTxIndex(
25✔
607
                b.chainConn, confRequest, txNotFoundErr,
25✔
608
        )
25✔
609

25✔
610
        // We'll then check the status of the transaction lookup returned to
25✔
611
        // determine whether we should proceed with any fallback methods.
25✔
612
        switch {
25✔
613

614
        // We failed querying the index for the transaction, fall back to
615
        // scanning manually.
616
        case err != nil:
8✔
617
                chainntnfs.Log.Debugf("Unable to determine confirmation of %v "+
8✔
618
                        "through the backend's txindex (%v), scanning manually",
8✔
619
                        confRequest.TxID, err)
8✔
620

8✔
621
                return b.confDetailsManually(
8✔
622
                        confRequest, startHeight, endHeight,
8✔
623
                )
8✔
624

625
        // The transaction was found within the node's mempool.
626
        case txStatus == chainntnfs.TxFoundMempool:
15✔
627

628
        // The transaction was found within the node's txindex.
629
        case txStatus == chainntnfs.TxFoundIndex:
2✔
630

631
        // The transaction was not found within the node's mempool or txindex.
632
        case txStatus == chainntnfs.TxNotFoundIndex:
2✔
633

634
        // Unexpected txStatus returned.
635
        default:
×
636
                return nil, txStatus,
×
637
                        fmt.Errorf("Got unexpected txConfStatus: %v", txStatus)
×
638
        }
639

640
        return txConf, txStatus, nil
17✔
641
}
642

643
// confDetailsManually looks up whether a transaction/output script has already
644
// been included in a block in the active chain by scanning the chain's blocks
645
// within the given range. If the transaction/output script is found, its
646
// confirmation details are returned. Otherwise, nil is returned.
647
func (b *BtcdNotifier) confDetailsManually(confRequest chainntnfs.ConfRequest,
648
        startHeight, endHeight uint32) (*chainntnfs.TxConfirmation,
649
        chainntnfs.TxConfStatus, error) {
24✔
650

24✔
651
        // Begin scanning blocks at every height to determine where the
24✔
652
        // transaction was included in.
24✔
653
        for height := endHeight; height >= startHeight && height > 0; height-- {
61✔
654
                // Ensure we haven't been requested to shut down before
37✔
655
                // processing the next height.
37✔
656
                select {
37✔
657
                case <-b.quit:
×
658
                        return nil, chainntnfs.TxNotFoundManually,
×
659
                                chainntnfs.ErrChainNotifierShuttingDown
×
660
                default:
37✔
661
                }
662

663
                blockHash, err := b.chainConn.GetBlockHash(int64(height))
37✔
664
                if err != nil {
37✔
665
                        return nil, chainntnfs.TxNotFoundManually,
×
666
                                fmt.Errorf("unable to get hash from block "+
×
667
                                        "with height %d", height)
×
668
                }
×
669

670
                // TODO: fetch the neutrino filters instead.
671
                block, err := b.GetBlock(blockHash)
37✔
672
                if err != nil {
37✔
673
                        return nil, chainntnfs.TxNotFoundManually,
×
674
                                fmt.Errorf("unable to get block with hash "+
×
675
                                        "%v: %v", blockHash, err)
×
676
                }
×
677

678
                // For every transaction in the block, check which one matches
679
                // our request. If we find one that does, we can dispatch its
680
                // confirmation details.
681
                for txIndex, tx := range block.Transactions {
97✔
682
                        if !confRequest.MatchesTx(tx) {
115✔
683
                                continue
55✔
684
                        }
685

686
                        return &chainntnfs.TxConfirmation{
5✔
687
                                Tx:          tx.Copy(),
5✔
688
                                BlockHash:   blockHash,
5✔
689
                                BlockHeight: height,
5✔
690
                                TxIndex:     uint32(txIndex),
5✔
691
                                Block:       block,
5✔
692
                        }, chainntnfs.TxFoundManually, nil
5✔
693
                }
694
        }
695

696
        // If we reach here, then we were not able to find the transaction
697
        // within a block, so we avoid returning an error.
698
        return nil, chainntnfs.TxNotFoundManually, nil
19✔
699
}
700

701
// handleBlockConnected applies a chain update for a new block. Any watched
702
// transactions included this block will processed to either send notifications
703
// now or after numConfirmations confs.
704
// TODO(halseth): this is reusing the neutrino notifier implementation, unify
705
// them.
706
func (b *BtcdNotifier) handleBlockConnected(epoch chainntnfs.BlockEpoch) error {
897✔
707
        // First, we'll fetch the raw block as we'll need to gather all the
897✔
708
        // transactions to determine whether any are relevant to our registered
897✔
709
        // clients.
897✔
710
        rawBlock, err := b.GetBlock(epoch.Hash)
897✔
711
        if err != nil {
897✔
712
                return fmt.Errorf("unable to get block: %w", err)
×
713
        }
×
714
        newBlock := &filteredBlock{
897✔
715
                hash:    *epoch.Hash,
897✔
716
                height:  uint32(epoch.Height),
897✔
717
                block:   btcutil.NewBlock(rawBlock),
897✔
718
                connect: true,
897✔
719
        }
897✔
720

897✔
721
        // We'll then extend the txNotifier's height with the information of
897✔
722
        // this new block, which will handle all of the notification logic for
897✔
723
        // us.
897✔
724
        err = b.txNotifier.ConnectTip(newBlock.block, newBlock.height)
897✔
725
        if err != nil {
897✔
726
                return fmt.Errorf("unable to connect tip: %w", err)
×
727
        }
×
728

729
        chainntnfs.Log.Infof("New block: height=%v, sha=%v", epoch.Height,
897✔
730
                epoch.Hash)
897✔
731

897✔
732
        // Now that we've guaranteed the new block extends the txNotifier's
897✔
733
        // current tip, we'll proceed to dispatch notifications to all of our
897✔
734
        // registered clients whom have had notifications fulfilled. Before
897✔
735
        // doing so, we'll make sure update our in memory state in order to
897✔
736
        // satisfy any client requests based upon the new block.
897✔
737
        b.bestBlock = epoch
897✔
738

897✔
739
        err = b.txNotifier.NotifyHeight(uint32(epoch.Height))
897✔
740
        if err != nil {
897✔
741
                return fmt.Errorf("unable to notify height: %w", err)
×
742
        }
×
743

744
        b.notifyBlockEpochs(
897✔
745
                epoch.Height, epoch.Hash, epoch.BlockHeader,
897✔
746
        )
897✔
747

897✔
748
        return nil
897✔
749
}
750

751
// notifyBlockEpochs notifies all registered block epoch clients of the newly
752
// connected block to the main chain.
753
func (b *BtcdNotifier) notifyBlockEpochs(newHeight int32,
754
        newSha *chainhash.Hash, blockHeader *wire.BlockHeader) {
897✔
755

897✔
756
        for _, client := range b.blockEpochClients {
1,169✔
757
                b.notifyBlockEpochClient(
272✔
758
                        client, newHeight, newSha, blockHeader,
272✔
759
                )
272✔
760
        }
272✔
761
}
762

763
// notifyBlockEpochClient sends a registered block epoch client a notification
764
// about a specific block.
765
func (b *BtcdNotifier) notifyBlockEpochClient(epochClient *blockEpochRegistration,
766
        height int32, sha *chainhash.Hash, blockHeader *wire.BlockHeader) {
341✔
767

341✔
768
        epoch := &chainntnfs.BlockEpoch{
341✔
769
                Height:      height,
341✔
770
                Hash:        sha,
341✔
771
                BlockHeader: blockHeader,
341✔
772
        }
341✔
773

341✔
774
        select {
341✔
775
        case epochClient.epochQueue.ChanIn() <- epoch:
341✔
776
        case <-epochClient.cancelChan:
×
777
        case <-b.quit:
×
778
        }
779
}
780

781
// RegisterSpendNtfn registers an intent to be notified once the target
782
// outpoint/output script has been spent by a transaction on-chain. When
783
// intending to be notified of the spend of an output script, a nil outpoint
784
// must be used. The heightHint should represent the earliest height in the
785
// chain of the transaction that spent the outpoint/output script.
786
//
787
// Once a spend of has been detected, the details of the spending event will be
788
// sent across the 'Spend' channel.
789
func (b *BtcdNotifier) RegisterSpendNtfn(outpoint *wire.OutPoint,
790
        pkScript []byte, heightHint uint32) (*chainntnfs.SpendEvent, error) {
27✔
791

27✔
792
        // Register the conf notification with the TxNotifier. A non-nil value
27✔
793
        // for `dispatch` will be returned if we are required to perform a
27✔
794
        // manual scan for the confirmation. Otherwise the notifier will begin
27✔
795
        // watching at tip for the transaction to confirm.
27✔
796
        ntfn, err := b.txNotifier.RegisterSpend(outpoint, pkScript, heightHint)
27✔
797
        if err != nil {
28✔
798
                return nil, err
1✔
799
        }
1✔
800

801
        // We'll then request the backend to notify us when it has detected the
802
        // outpoint/output script as spent.
803
        //
804
        // TODO(wilmer): use LoadFilter API instead.
805
        if outpoint == nil || *outpoint == chainntnfs.ZeroOutPoint {
40✔
806
                _, addrs, _, err := txscript.ExtractPkScriptAddrs(
13✔
807
                        pkScript, b.chainParams,
13✔
808
                )
13✔
809
                if err != nil {
13✔
810
                        return nil, fmt.Errorf("unable to parse script: %w",
×
811
                                err)
×
812
                }
×
813
                if err := b.chainConn.NotifyReceived(addrs); err != nil {
13✔
814
                        return nil, err
×
815
                }
×
816
        } else {
14✔
817
                ops := []*wire.OutPoint{outpoint}
14✔
818
                if err := b.chainConn.NotifySpent(ops); err != nil {
14✔
819
                        return nil, err
×
820
                }
×
821
        }
822

823
        // If the txNotifier didn't return any details to perform a historical
824
        // scan of the chain, then we can return early as there's nothing left
825
        // for us to do.
826
        if ntfn.HistoricalDispatch == nil {
51✔
827
                return ntfn.Event, nil
24✔
828
        }
24✔
829

830
        // Otherwise, we'll need to dispatch a historical rescan to determine if
831
        // the outpoint was already spent at a previous height.
832
        //
833
        // We'll short-circuit the path when dispatching the spend of a script,
834
        // rather than an outpoint, as there aren't any additional checks we can
835
        // make for scripts.
836
        if outpoint == nil || *outpoint == chainntnfs.ZeroOutPoint {
5✔
837
                startHash, err := b.chainConn.GetBlockHash(
1✔
838
                        int64(ntfn.HistoricalDispatch.StartHeight),
1✔
839
                )
1✔
840
                if err != nil {
1✔
841
                        return nil, err
×
842
                }
×
843

844
                // TODO(wilmer): add retry logic if rescan fails?
845
                _, addrs, _, err := txscript.ExtractPkScriptAddrs(
1✔
846
                        pkScript, b.chainParams,
1✔
847
                )
1✔
848
                if err != nil {
1✔
849
                        return nil, fmt.Errorf("unable to parse address: %w",
×
850
                                err)
×
851
                }
×
852

853
                asyncResult := b.chainConn.RescanAsync(startHash, addrs, nil)
1✔
854
                go func() {
2✔
855
                        if rescanErr := asyncResult.Receive(); rescanErr != nil {
1✔
856
                                chainntnfs.Log.Errorf("Rescan to determine "+
×
857
                                        "the spend details of %v failed: %v",
×
858
                                        ntfn.HistoricalDispatch.SpendRequest,
×
859
                                        rescanErr)
×
860
                        }
×
861
                }()
862

863
                return ntfn.Event, nil
1✔
864
        }
865

866
        // When dispatching spends of outpoints, there are a number of checks we
867
        // can make to start our rescan from a better height or completely avoid
868
        // it.
869
        //
870
        // We'll start by checking the backend's UTXO set to determine whether
871
        // the outpoint has been spent. If it hasn't, we can return to the
872
        // caller as well.
873
        txOut, err := b.chainConn.GetTxOut(&outpoint.Hash, outpoint.Index, true)
3✔
874
        if err != nil {
3✔
875
                return nil, err
×
876
        }
×
877
        if txOut != nil {
5✔
878
                // We'll let the txNotifier know the outpoint is still unspent
2✔
879
                // in order to begin updating its spend hint.
2✔
880
                err := b.txNotifier.UpdateSpendDetails(
2✔
881
                        ntfn.HistoricalDispatch.SpendRequest, nil,
2✔
882
                )
2✔
883
                if err != nil {
2✔
884
                        return nil, err
×
885
                }
×
886

887
                return ntfn.Event, nil
2✔
888
        }
889

890
        // Since the outpoint was spent, as it no longer exists within the UTXO
891
        // set, we'll determine when it happened by scanning the chain. We'll
892
        // begin by fetching the block hash of our starting height.
893
        startHash, err := b.chainConn.GetBlockHash(
2✔
894
                int64(ntfn.HistoricalDispatch.StartHeight),
2✔
895
        )
2✔
896
        if err != nil {
2✔
897
                return nil, fmt.Errorf("unable to get block hash for height "+
×
898
                        "%d: %v", ntfn.HistoricalDispatch.StartHeight, err)
×
899
        }
×
900

901
        // As a minimal optimization, we'll query the backend's transaction
902
        // index (if enabled) to determine if we have a better rescan starting
903
        // height. We can do this as the GetRawTransaction call will return the
904
        // hash of the block it was included in within the chain.
905
        tx, err := b.chainConn.GetRawTransactionVerbose(&outpoint.Hash)
2✔
906
        if err != nil {
4✔
907
                // Avoid returning an error if the transaction was not found to
2✔
908
                // proceed with fallback methods.
2✔
909
                jsonErr, ok := err.(*btcjson.RPCError)
2✔
910
                if !ok || jsonErr.Code != btcjson.ErrRPCNoTxInfo {
2✔
911
                        return nil, fmt.Errorf("unable to query for txid %v: "+
×
912
                                "%w", outpoint.Hash, err)
×
913
                }
×
914
        }
915

916
        // If the transaction index was enabled, we'll use the block's hash to
917
        // retrieve its height and check whether it provides a better starting
918
        // point for our rescan.
919
        if tx != nil {
3✔
920
                // If the transaction containing the outpoint hasn't confirmed
1✔
921
                // on-chain, then there's no need to perform a rescan.
1✔
922
                if tx.BlockHash == "" {
2✔
923
                        return ntfn.Event, nil
1✔
924
                }
1✔
925

926
                blockHash, err := chainhash.NewHashFromStr(tx.BlockHash)
1✔
927
                if err != nil {
1✔
928
                        return nil, err
×
929
                }
×
930
                blockHeader, err := b.chainConn.GetBlockHeaderVerbose(blockHash)
1✔
931
                if err != nil {
1✔
932
                        return nil, fmt.Errorf("unable to get header for "+
×
933
                                "block %v: %v", blockHash, err)
×
934
                }
×
935

936
                spentHeight := uint32(blockHeader.Height)
1✔
937
                chainntnfs.Log.Debugf("Outpoint(%v) has spent at height %v",
1✔
938
                        outpoint, spentHeight)
1✔
939

1✔
940
                // Since the tx has already been spent at spentHeight, the
1✔
941
                // heightHint specified by the caller is no longer relevant. We
1✔
942
                // now update the starting height to be the spent height to make
1✔
943
                // sure we won't miss it in the rescan.
1✔
944
                if spentHeight != ntfn.HistoricalDispatch.StartHeight {
2✔
945
                        startHash, err = b.chainConn.GetBlockHash(
1✔
946
                                int64(spentHeight),
1✔
947
                        )
1✔
948
                        if err != nil {
1✔
949
                                return nil, fmt.Errorf("unable to get block "+
×
950
                                        "hash for height %d: %v",
×
951
                                        blockHeader.Height, err)
×
952
                        }
×
953

954
                        ntfn.HistoricalDispatch.StartHeight = spentHeight
1✔
955
                }
956
        }
957

958
        // Now that we've determined the best starting point for our rescan,
959
        // we can go ahead and dispatch it.
960
        //
961
        // In order to ensure that we don't block the caller on what may be a
962
        // long rescan, we'll launch a new goroutine to handle the async result
963
        // of the rescan. We purposefully prevent from adding this goroutine to
964
        // the WaitGroup as we cannot wait for a quit signal due to the
965
        // asyncResult channel not being exposed.
966
        //
967
        // TODO(wilmer): add retry logic if rescan fails?
968
        asyncResult := b.chainConn.RescanAsync(
2✔
969
                startHash, nil, []*wire.OutPoint{outpoint},
2✔
970
        )
2✔
971
        go func() {
4✔
972
                if rescanErr := asyncResult.Receive(); rescanErr != nil {
2✔
973
                        chainntnfs.Log.Errorf("Rescan to determine the spend "+
×
974
                                "details of %v failed: %v", outpoint, rescanErr)
×
975
                }
×
976
        }()
977

978
        return ntfn.Event, nil
2✔
979
}
980

981
// RegisterConfirmationsNtfn registers an intent to be notified once the target
982
// txid/output script has reached numConfs confirmations on-chain. When
983
// intending to be notified of the confirmation of an output script, a nil txid
984
// must be used. The heightHint should represent the earliest height at which
985
// the txid/output script could have been included in the chain.
986
//
987
// Progress on the number of confirmations left can be read from the 'Updates'
988
// channel. Once it has reached all of its confirmations, a notification will be
989
// sent across the 'Confirmed' channel.
990
func (b *BtcdNotifier) RegisterConfirmationsNtfn(txid *chainhash.Hash,
991
        pkScript []byte, numConfs, heightHint uint32,
992
        opts ...chainntnfs.NotifierOption) (*chainntnfs.ConfirmationEvent, error) {
49✔
993

49✔
994
        // Register the conf notification with the TxNotifier. A non-nil value
49✔
995
        // for `dispatch` will be returned if we are required to perform a
49✔
996
        // manual scan for the confirmation. Otherwise the notifier will begin
49✔
997
        // watching at tip for the transaction to confirm.
49✔
998
        ntfn, err := b.txNotifier.RegisterConf(
49✔
999
                txid, pkScript, numConfs, heightHint, opts...,
49✔
1000
        )
49✔
1001
        if err != nil {
49✔
1002
                return nil, err
×
1003
        }
×
1004

1005
        if ntfn.HistoricalDispatch == nil {
64✔
1006
                return ntfn.Event, nil
15✔
1007
        }
15✔
1008

1009
        select {
35✔
1010
        case b.notificationRegistry <- ntfn.HistoricalDispatch:
35✔
1011
                return ntfn.Event, nil
35✔
1012
        case <-b.quit:
×
1013
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
1014
        }
1015
}
1016

1017
// blockEpochRegistration represents a client's intent to receive a
1018
// notification with each newly connected block.
1019
type blockEpochRegistration struct {
1020
        epochID uint64
1021

1022
        epochChan chan *chainntnfs.BlockEpoch
1023

1024
        epochQueue *queue.ConcurrentQueue
1025

1026
        bestBlock *chainntnfs.BlockEpoch
1027

1028
        errorChan chan error
1029

1030
        cancelChan chan struct{}
1031

1032
        wg sync.WaitGroup
1033
}
1034

1035
// epochCancel is a message sent to the BtcdNotifier when a client wishes to
1036
// cancel an outstanding epoch notification that has yet to be dispatched.
1037
type epochCancel struct {
1038
        epochID uint64
1039
}
1040

1041
// RegisterBlockEpochNtfn returns a BlockEpochEvent which subscribes the
1042
// caller to receive notifications, of each new block connected to the main
1043
// chain. Clients have the option of passing in their best known block, which
1044
// the notifier uses to check if they are behind on blocks and catch them up. If
1045
// they do not provide one, then a notification will be dispatched immediately
1046
// for the current tip of the chain upon a successful registration.
1047
func (b *BtcdNotifier) RegisterBlockEpochNtfn(
1048
        bestBlock *chainntnfs.BlockEpoch) (*chainntnfs.BlockEpochEvent, error) {
25✔
1049

25✔
1050
        reg := &blockEpochRegistration{
25✔
1051
                epochQueue: queue.NewConcurrentQueue(20),
25✔
1052
                epochChan:  make(chan *chainntnfs.BlockEpoch, 20),
25✔
1053
                cancelChan: make(chan struct{}),
25✔
1054
                epochID:    atomic.AddUint64(&b.epochClientCounter, 1),
25✔
1055
                bestBlock:  bestBlock,
25✔
1056
                errorChan:  make(chan error, 1),
25✔
1057
        }
25✔
1058

25✔
1059
        reg.epochQueue.Start()
25✔
1060

25✔
1061
        // Before we send the request to the main goroutine, we'll launch a new
25✔
1062
        // goroutine to proxy items added to our queue to the client itself.
25✔
1063
        // This ensures that all notifications are received *in order*.
25✔
1064
        reg.wg.Add(1)
25✔
1065
        go func() {
50✔
1066
                defer reg.wg.Done()
25✔
1067

25✔
1068
                for {
344✔
1069
                        select {
319✔
1070
                        case ntfn := <-reg.epochQueue.ChanOut():
297✔
1071
                                blockNtfn := ntfn.(*chainntnfs.BlockEpoch)
297✔
1072
                                select {
297✔
1073
                                case reg.epochChan <- blockNtfn:
295✔
1074

1075
                                case <-reg.cancelChan:
1✔
1076
                                        return
1✔
1077

1078
                                case <-b.quit:
2✔
1079
                                        return
2✔
1080
                                }
1081

1082
                        case <-reg.cancelChan:
2✔
1083
                                return
2✔
1084

1085
                        case <-b.quit:
22✔
1086
                                return
22✔
1087
                        }
1088
                }
1089
        }()
1090

1091
        select {
25✔
1092
        case <-b.quit:
×
1093
                // As we're exiting before the registration could be sent,
×
1094
                // we'll stop the queue now ourselves.
×
1095
                reg.epochQueue.Stop()
×
1096

×
1097
                return nil, errors.New("chainntnfs: system interrupt while " +
×
1098
                        "attempting to register for block epoch notification.")
×
1099
        case b.notificationRegistry <- reg:
25✔
1100
                return &chainntnfs.BlockEpochEvent{
25✔
1101
                        Epochs: reg.epochChan,
25✔
1102
                        Cancel: func() {
27✔
1103
                                cancel := &epochCancel{
2✔
1104
                                        epochID: reg.epochID,
2✔
1105
                                }
2✔
1106

2✔
1107
                                // Submit epoch cancellation to notification dispatcher.
2✔
1108
                                select {
2✔
1109
                                case b.notificationCancels <- cancel:
2✔
1110
                                        // Cancellation is being handled, drain
2✔
1111
                                        // the epoch channel until it is closed
2✔
1112
                                        // before yielding to caller.
2✔
1113
                                        for {
5✔
1114
                                                select {
3✔
1115
                                                case _, ok := <-reg.epochChan:
3✔
1116
                                                        if !ok {
5✔
1117
                                                                return
2✔
1118
                                                        }
2✔
1119
                                                case <-b.quit:
×
1120
                                                        return
×
1121
                                                }
1122
                                        }
1123
                                case <-b.quit:
1✔
1124
                                }
1125
                        },
1126
                }, nil
1127
        }
1128
}
1129

1130
// GetBlock is used to retrieve the block with the given hash. This function
1131
// wraps the blockCache's GetBlock function.
1132
func (b *BtcdNotifier) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock,
1133
        error) {
934✔
1134

934✔
1135
        return b.blockCache.GetBlock(hash, b.chainConn.GetBlock)
934✔
1136
}
934✔
1137

1138
// SubscribeMempoolSpent allows the caller to register a subscription to watch
1139
// for a spend of an outpoint in the mempool.The event will be dispatched once
1140
// the outpoint is spent in the mempool.
1141
//
1142
// NOTE: part of the MempoolWatcher interface.
1143
func (b *BtcdNotifier) SubscribeMempoolSpent(
1144
        outpoint wire.OutPoint) (*chainntnfs.MempoolSpendEvent, error) {
1✔
1145

1✔
1146
        event := b.memNotifier.SubscribeInput(outpoint)
1✔
1147

1✔
1148
        ops := []*wire.OutPoint{&outpoint}
1✔
1149

1✔
1150
        return event, b.chainConn.NotifySpent(ops)
1✔
1151
}
1✔
1152

1153
// CancelMempoolSpendEvent allows the caller to cancel a subscription to watch
1154
// for a spend of an outpoint in the mempool.
1155
//
1156
// NOTE: part of the MempoolWatcher interface.
1157
func (b *BtcdNotifier) CancelMempoolSpendEvent(
1158
        sub *chainntnfs.MempoolSpendEvent) {
1✔
1159

1✔
1160
        b.memNotifier.UnsubscribeEvent(sub)
1✔
1161
}
1✔
1162

1163
// LookupInputMempoolSpend takes an outpoint and queries the mempool to find
1164
// its spending tx. Returns the tx if found, otherwise fn.None.
1165
//
1166
// NOTE: part of the MempoolWatcher interface.
1167
func (b *BtcdNotifier) LookupInputMempoolSpend(
1168
        op wire.OutPoint) fn.Option[wire.MsgTx] {
1✔
1169

1✔
1170
        // Find the spending txid.
1✔
1171
        txid, found := b.chainConn.LookupInputMempoolSpend(op)
1✔
1172
        if !found {
2✔
1173
                return fn.None[wire.MsgTx]()
1✔
1174
        }
1✔
1175

1176
        // Query the spending tx using the id.
1177
        tx, err := b.chainConn.GetRawTransaction(&txid)
1✔
1178
        if err != nil {
1✔
1179
                // TODO(yy): enable logging errors in this package.
×
1180
                return fn.None[wire.MsgTx]()
×
1181
        }
×
1182

1183
        return fn.Some(*tx.MsgTx().Copy())
1✔
1184
}
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