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

lightningnetwork / lnd / 15561477203

10 Jun 2025 01:54PM UTC coverage: 58.351% (-10.1%) from 68.487%
15561477203

Pull #9356

github

web-flow
Merge 6440b25db into c6d6d4c0b
Pull Request #9356: lnrpc: add incoming/outgoing channel ids filter to forwarding history request

33 of 36 new or added lines in 2 files covered. (91.67%)

28366 existing lines in 455 files now uncovered.

97715 of 167461 relevant lines covered (58.35%)

1.81 hits per line

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

73.57
/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) {
1✔
111

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

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

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

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

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

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

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

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

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

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

150
        notifier.chainConn = chainRPC
1✔
151

1✔
152
        return notifier, nil
1✔
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 {
1✔
158
        var startErr error
1✔
159
        b.start.Do(func() {
2✔
160
                startErr = b.startNotifier()
1✔
161
        })
1✔
162

163
        return startErr
1✔
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 {
1✔
173
        // Already shutting down?
1✔
174
        if atomic.AddInt32(&b.stopped, 1) != 1 {
1✔
175
                return nil
×
176
        }
×
177

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

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

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

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

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

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

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

1✔
204
        return nil
1✔
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 {
1✔
210
        chainntnfs.Log.Infof("btcd notifier starting...")
1✔
211

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

1✔
218
        // Connect to btcd, and register for notifications on connected, and
1✔
219
        // disconnected blocks.
1✔
220
        if err := b.chainConn.Connect(20); err != nil {
1✔
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 {
1✔
232
                b.txUpdates.Stop()
×
233
                b.chainUpdates.Stop()
×
234
                return err
×
235
        }
×
236

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

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

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

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

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

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

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

1✔
271
        return nil
1✔
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) {
1✔
278
        // Append this new chain update to the end of the queue of new chain
1✔
279
        // updates.
1✔
280
        select {
1✔
281
        case b.chainUpdates.ChanIn() <- &chainUpdate{
282
                blockHash:   hash,
283
                blockHeight: height,
284
                connect:     true,
285
        }:
1✔
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) {
1✔
311
        // Append this new chain update to the end of the queue of new chain
1✔
312
        // updates.
1✔
313
        select {
1✔
314
        case b.chainUpdates.ChanIn() <- &chainUpdate{
315
                blockHash:   hash,
316
                blockHeight: height,
317
                connect:     false,
318
        }:
1✔
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) {
1✔
326
        // Append this new transaction update to the end of the queue of new
1✔
327
        // chain updates.
1✔
328
        select {
1✔
329
        case b.txUpdates.ChanIn() <- &txUpdate{tx, details}:
1✔
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() {
1✔
338
        defer b.wg.Done()
1✔
339

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

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

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

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

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

1✔
384
                                        confDetails, _, err := b.historicalConfDetails(
1✔
385
                                                msg.ConfRequest,
1✔
386
                                                msg.StartHeight, msg.EndHeight,
1✔
387
                                        )
1✔
388
                                        if err != nil {
1✔
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(
1✔
401
                                                msg.ConfRequest, confDetails,
1✔
402
                                        )
1✔
403
                                        if err != nil {
1✔
404
                                                chainntnfs.Log.Error(err)
×
405
                                        }
×
406
                                }(msg)
407

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

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

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

1✔
423
                                        msg.errorChan <- nil
1✔
424
                                        continue
1✔
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(
1✔
431
                                        b.chainConn, msg.bestBlock,
1✔
432
                                        b.bestBlock.Height, true,
1✔
433
                                )
1✔
434
                                if err != nil {
1✔
435
                                        msg.errorChan <- err
×
436
                                        continue
×
437
                                }
438

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

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

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

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

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

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

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

508
                        newBestBlock, err := chainntnfs.RewindChain(
1✔
509
                                b.chainConn, b.txNotifier, b.bestBlock,
1✔
510
                                update.blockHeight-1,
1✔
511
                        )
1✔
512
                        if err != nil {
2✔
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
1✔
521

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

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

1✔
530
                        // Unwrap values.
1✔
531
                        if newSpend.details == nil {
2✔
532
                                isMempool = true
1✔
533
                        } else {
2✔
534
                                height = uint32(newSpend.details.Height)
1✔
535
                        }
1✔
536

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

540
                case <-b.quit:
1✔
541
                        break out
1✔
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) {
1✔
552

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

562
                return
1✔
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)
1✔
568
        if err != nil {
1✔
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)
1✔
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) {
1✔
590

1✔
591
        // If a txid was not provided, then we should dispatch upon seeing the
1✔
592
        // script on-chain, so we'll short-circuit straight to scanning manually
1✔
593
        // as there doesn't exist a script index to query.
1✔
594
        if confRequest.TxID == chainntnfs.ZeroHash {
1✔
UNCOV
595
                return b.confDetailsManually(
×
UNCOV
596
                        confRequest, startHeight, endHeight,
×
UNCOV
597
                )
×
UNCOV
598
        }
×
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"
1✔
606
        txConf, txStatus, err := chainntnfs.ConfDetailsFromTxIndex(
1✔
607
                b.chainConn, confRequest, txNotFoundErr,
1✔
608
        )
1✔
609

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

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

×
UNCOV
621
                return b.confDetailsManually(
×
UNCOV
622
                        confRequest, startHeight, endHeight,
×
UNCOV
623
                )
×
624

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

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

631
        // The transaction was not found within the node's mempool or txindex.
632
        case txStatus == chainntnfs.TxNotFoundIndex:
1✔
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
1✔
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,
UNCOV
649
        chainntnfs.TxConfStatus, error) {
×
UNCOV
650

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

UNCOV
663
                blockHash, err := b.chainConn.GetBlockHash(int64(height))
×
UNCOV
664
                if err != nil {
×
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.
UNCOV
671
                block, err := b.GetBlock(blockHash)
×
UNCOV
672
                if err != nil {
×
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.
UNCOV
681
                for txIndex, tx := range block.Transactions {
×
UNCOV
682
                        if !confRequest.MatchesTx(tx) {
×
UNCOV
683
                                continue
×
684
                        }
685

UNCOV
686
                        return &chainntnfs.TxConfirmation{
×
UNCOV
687
                                Tx:          tx.Copy(),
×
UNCOV
688
                                BlockHash:   blockHash,
×
UNCOV
689
                                BlockHeight: height,
×
UNCOV
690
                                TxIndex:     uint32(txIndex),
×
UNCOV
691
                                Block:       block,
×
UNCOV
692
                        }, chainntnfs.TxFoundManually, nil
×
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.
UNCOV
698
        return nil, chainntnfs.TxNotFoundManually, nil
×
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 {
1✔
707
        // First, we'll fetch the raw block as we'll need to gather all the
1✔
708
        // transactions to determine whether any are relevant to our registered
1✔
709
        // clients.
1✔
710
        rawBlock, err := b.GetBlock(epoch.Hash)
1✔
711
        if err != nil {
1✔
712
                return fmt.Errorf("unable to get block: %w", err)
×
713
        }
×
714
        newBlock := &filteredBlock{
1✔
715
                hash:    *epoch.Hash,
1✔
716
                height:  uint32(epoch.Height),
1✔
717
                block:   btcutil.NewBlock(rawBlock),
1✔
718
                connect: true,
1✔
719
        }
1✔
720

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

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

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

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

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

1✔
748
        return nil
1✔
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) {
1✔
755

1✔
756
        for _, client := range b.blockEpochClients {
2✔
757
                b.notifyBlockEpochClient(
1✔
758
                        client, newHeight, newSha, blockHeader,
1✔
759
                )
1✔
760
        }
1✔
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) {
1✔
767

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

1✔
774
        select {
1✔
775
        case epochClient.epochQueue.ChanIn() <- epoch:
1✔
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) {
1✔
791

1✔
792
        // Register the conf notification with the TxNotifier. A non-nil value
1✔
793
        // for `dispatch` will be returned if we are required to perform a
1✔
794
        // manual scan for the confirmation. Otherwise the notifier will begin
1✔
795
        // watching at tip for the transaction to confirm.
1✔
796
        ntfn, err := b.txNotifier.RegisterSpend(outpoint, pkScript, heightHint)
1✔
797
        if err != nil {
2✔
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 {
1✔
UNCOV
806
                _, addrs, _, err := txscript.ExtractPkScriptAddrs(
×
UNCOV
807
                        pkScript, b.chainParams,
×
UNCOV
808
                )
×
UNCOV
809
                if err != nil {
×
810
                        return nil, fmt.Errorf("unable to parse script: %w",
×
811
                                err)
×
812
                }
×
UNCOV
813
                if err := b.chainConn.NotifyReceived(addrs); err != nil {
×
814
                        return nil, err
×
815
                }
×
816
        } else {
1✔
817
                ops := []*wire.OutPoint{outpoint}
1✔
818
                if err := b.chainConn.NotifySpent(ops); err != nil {
1✔
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 {
2✔
827
                return ntfn.Event, nil
1✔
828
        }
1✔
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 {
1✔
UNCOV
837
                startHash, err := b.chainConn.GetBlockHash(
×
UNCOV
838
                        int64(ntfn.HistoricalDispatch.StartHeight),
×
UNCOV
839
                )
×
UNCOV
840
                if err != nil {
×
841
                        return nil, err
×
842
                }
×
843

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

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

UNCOV
863
                return ntfn.Event, nil
×
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)
1✔
874
        if err != nil {
1✔
875
                return nil, err
×
876
        }
×
877
        if txOut != nil {
2✔
878
                // We'll let the txNotifier know the outpoint is still unspent
1✔
879
                // in order to begin updating its spend hint.
1✔
880
                err := b.txNotifier.UpdateSpendDetails(
1✔
881
                        ntfn.HistoricalDispatch.SpendRequest, nil,
1✔
882
                )
1✔
883
                if err != nil {
1✔
884
                        return nil, err
×
885
                }
×
886

887
                return ntfn.Event, nil
1✔
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(
1✔
894
                int64(ntfn.HistoricalDispatch.StartHeight),
1✔
895
        )
1✔
896
        if err != nil {
1✔
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)
1✔
906
        if err != nil {
2✔
907
                // Avoid returning an error if the transaction was not found to
1✔
908
                // proceed with fallback methods.
1✔
909
                jsonErr, ok := err.(*btcjson.RPCError)
1✔
910
                if !ok || jsonErr.Code != btcjson.ErrRPCNoTxInfo {
1✔
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 {
2✔
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
                if uint32(blockHeader.Height) > ntfn.HistoricalDispatch.StartHeight {
2✔
937
                        startHash, err = b.chainConn.GetBlockHash(
1✔
938
                                int64(blockHeader.Height),
1✔
939
                        )
1✔
940
                        if err != nil {
1✔
941
                                return nil, fmt.Errorf("unable to get block "+
×
942
                                        "hash for height %d: %v",
×
943
                                        blockHeader.Height, err)
×
944
                        }
×
945
                }
946
        }
947

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

968
        return ntfn.Event, nil
1✔
969
}
970

971
// RegisterConfirmationsNtfn registers an intent to be notified once the target
972
// txid/output script has reached numConfs confirmations on-chain. When
973
// intending to be notified of the confirmation of an output script, a nil txid
974
// must be used. The heightHint should represent the earliest height at which
975
// the txid/output script could have been included in the chain.
976
//
977
// Progress on the number of confirmations left can be read from the 'Updates'
978
// channel. Once it has reached all of its confirmations, a notification will be
979
// sent across the 'Confirmed' channel.
980
func (b *BtcdNotifier) RegisterConfirmationsNtfn(txid *chainhash.Hash,
981
        pkScript []byte, numConfs, heightHint uint32,
982
        opts ...chainntnfs.NotifierOption) (*chainntnfs.ConfirmationEvent, error) {
1✔
983

1✔
984
        // Register the conf notification with the TxNotifier. A non-nil value
1✔
985
        // for `dispatch` will be returned if we are required to perform a
1✔
986
        // manual scan for the confirmation. Otherwise the notifier will begin
1✔
987
        // watching at tip for the transaction to confirm.
1✔
988
        ntfn, err := b.txNotifier.RegisterConf(
1✔
989
                txid, pkScript, numConfs, heightHint, opts...,
1✔
990
        )
1✔
991
        if err != nil {
1✔
992
                return nil, err
×
993
        }
×
994

995
        if ntfn.HistoricalDispatch == nil {
2✔
996
                return ntfn.Event, nil
1✔
997
        }
1✔
998

999
        select {
1✔
1000
        case b.notificationRegistry <- ntfn.HistoricalDispatch:
1✔
1001
                return ntfn.Event, nil
1✔
1002
        case <-b.quit:
×
1003
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
1004
        }
1005
}
1006

1007
// blockEpochRegistration represents a client's intent to receive a
1008
// notification with each newly connected block.
1009
type blockEpochRegistration struct {
1010
        epochID uint64
1011

1012
        epochChan chan *chainntnfs.BlockEpoch
1013

1014
        epochQueue *queue.ConcurrentQueue
1015

1016
        bestBlock *chainntnfs.BlockEpoch
1017

1018
        errorChan chan error
1019

1020
        cancelChan chan struct{}
1021

1022
        wg sync.WaitGroup
1023
}
1024

1025
// epochCancel is a message sent to the BtcdNotifier when a client wishes to
1026
// cancel an outstanding epoch notification that has yet to be dispatched.
1027
type epochCancel struct {
1028
        epochID uint64
1029
}
1030

1031
// RegisterBlockEpochNtfn returns a BlockEpochEvent which subscribes the
1032
// caller to receive notifications, of each new block connected to the main
1033
// chain. Clients have the option of passing in their best known block, which
1034
// the notifier uses to check if they are behind on blocks and catch them up. If
1035
// they do not provide one, then a notification will be dispatched immediately
1036
// for the current tip of the chain upon a successful registration.
1037
func (b *BtcdNotifier) RegisterBlockEpochNtfn(
1038
        bestBlock *chainntnfs.BlockEpoch) (*chainntnfs.BlockEpochEvent, error) {
1✔
1039

1✔
1040
        reg := &blockEpochRegistration{
1✔
1041
                epochQueue: queue.NewConcurrentQueue(20),
1✔
1042
                epochChan:  make(chan *chainntnfs.BlockEpoch, 20),
1✔
1043
                cancelChan: make(chan struct{}),
1✔
1044
                epochID:    atomic.AddUint64(&b.epochClientCounter, 1),
1✔
1045
                bestBlock:  bestBlock,
1✔
1046
                errorChan:  make(chan error, 1),
1✔
1047
        }
1✔
1048

1✔
1049
        reg.epochQueue.Start()
1✔
1050

1✔
1051
        // Before we send the request to the main goroutine, we'll launch a new
1✔
1052
        // goroutine to proxy items added to our queue to the client itself.
1✔
1053
        // This ensures that all notifications are received *in order*.
1✔
1054
        reg.wg.Add(1)
1✔
1055
        go func() {
2✔
1056
                defer reg.wg.Done()
1✔
1057

1✔
1058
                for {
2✔
1059
                        select {
1✔
1060
                        case ntfn := <-reg.epochQueue.ChanOut():
1✔
1061
                                blockNtfn := ntfn.(*chainntnfs.BlockEpoch)
1✔
1062
                                select {
1✔
1063
                                case reg.epochChan <- blockNtfn:
1✔
1064

1065
                                case <-reg.cancelChan:
1✔
1066
                                        return
1✔
1067

UNCOV
1068
                                case <-b.quit:
×
UNCOV
1069
                                        return
×
1070
                                }
1071

1072
                        case <-reg.cancelChan:
1✔
1073
                                return
1✔
1074

1075
                        case <-b.quit:
1✔
1076
                                return
1✔
1077
                        }
1078
                }
1079
        }()
1080

1081
        select {
1✔
1082
        case <-b.quit:
×
1083
                // As we're exiting before the registration could be sent,
×
1084
                // we'll stop the queue now ourselves.
×
1085
                reg.epochQueue.Stop()
×
1086

×
1087
                return nil, errors.New("chainntnfs: system interrupt while " +
×
1088
                        "attempting to register for block epoch notification.")
×
1089
        case b.notificationRegistry <- reg:
1✔
1090
                return &chainntnfs.BlockEpochEvent{
1✔
1091
                        Epochs: reg.epochChan,
1✔
1092
                        Cancel: func() {
2✔
1093
                                cancel := &epochCancel{
1✔
1094
                                        epochID: reg.epochID,
1✔
1095
                                }
1✔
1096

1✔
1097
                                // Submit epoch cancellation to notification dispatcher.
1✔
1098
                                select {
1✔
1099
                                case b.notificationCancels <- cancel:
1✔
1100
                                        // Cancellation is being handled, drain
1✔
1101
                                        // the epoch channel until it is closed
1✔
1102
                                        // before yielding to caller.
1✔
1103
                                        for {
2✔
1104
                                                select {
1✔
1105
                                                case _, ok := <-reg.epochChan:
1✔
1106
                                                        if !ok {
2✔
1107
                                                                return
1✔
1108
                                                        }
1✔
1109
                                                case <-b.quit:
×
1110
                                                        return
×
1111
                                                }
1112
                                        }
1113
                                case <-b.quit:
1✔
1114
                                }
1115
                        },
1116
                }, nil
1117
        }
1118
}
1119

1120
// GetBlock is used to retrieve the block with the given hash. This function
1121
// wraps the blockCache's GetBlock function.
1122
func (b *BtcdNotifier) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock,
1123
        error) {
1✔
1124

1✔
1125
        return b.blockCache.GetBlock(hash, b.chainConn.GetBlock)
1✔
1126
}
1✔
1127

1128
// SubscribeMempoolSpent allows the caller to register a subscription to watch
1129
// for a spend of an outpoint in the mempool.The event will be dispatched once
1130
// the outpoint is spent in the mempool.
1131
//
1132
// NOTE: part of the MempoolWatcher interface.
1133
func (b *BtcdNotifier) SubscribeMempoolSpent(
1134
        outpoint wire.OutPoint) (*chainntnfs.MempoolSpendEvent, error) {
1✔
1135

1✔
1136
        event := b.memNotifier.SubscribeInput(outpoint)
1✔
1137

1✔
1138
        ops := []*wire.OutPoint{&outpoint}
1✔
1139

1✔
1140
        return event, b.chainConn.NotifySpent(ops)
1✔
1141
}
1✔
1142

1143
// CancelMempoolSpendEvent allows the caller to cancel a subscription to watch
1144
// for a spend of an outpoint in the mempool.
1145
//
1146
// NOTE: part of the MempoolWatcher interface.
1147
func (b *BtcdNotifier) CancelMempoolSpendEvent(
1148
        sub *chainntnfs.MempoolSpendEvent) {
1✔
1149

1✔
1150
        b.memNotifier.UnsubscribeEvent(sub)
1✔
1151
}
1✔
1152

1153
// LookupInputMempoolSpend takes an outpoint and queries the mempool to find
1154
// its spending tx. Returns the tx if found, otherwise fn.None.
1155
//
1156
// NOTE: part of the MempoolWatcher interface.
1157
func (b *BtcdNotifier) LookupInputMempoolSpend(
1158
        op wire.OutPoint) fn.Option[wire.MsgTx] {
1✔
1159

1✔
1160
        // Find the spending txid.
1✔
1161
        txid, found := b.chainConn.LookupInputMempoolSpend(op)
1✔
1162
        if !found {
2✔
1163
                return fn.None[wire.MsgTx]()
1✔
1164
        }
1✔
1165

1166
        // Query the spending tx using the id.
1167
        tx, err := b.chainConn.GetRawTransaction(&txid)
1✔
1168
        if err != nil {
1✔
1169
                // TODO(yy): enable logging errors in this package.
×
1170
                return fn.None[wire.MsgTx]()
×
1171
        }
×
1172

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